Mvc Ajax提交多个checkbox,也说绑定和提交select

Ajax Mvc的 checkbox

后端必须是List<T> ,T是ID类型,一般int 或guid

模型必须初始化List<T> 防止客户端没有提交任何值时空引用的问题,如果你喜欢每次都去判断下,那也不所谓。

class model{

public model(){

selectedValues = new List<int>(); //很重要!!!

}

public List<int> selectedValues{get;set;}

}

不能使用T[]数组,因为数组是只读的,没法Add。反驳我?走开,老子没说数组元素。

非逗号分隔传递多值的方法,就是带上索引。必须从0开始。

解决方案如下

<checkbox name="selectedValues[x]" value='1'>

<checkbox name="selectedValues[x]" value='1'>

<checkbox name="selectedValues[x]" value='1'>

<checkbox name="selectedValues[x]" value='1'>

<checkbox name="selectedValues[x]" value='1'>

把选中的处理好即可

mdcs.badValues = ['-1', '0', '@Guid.Empty'];
        mdcs.serializeForm = function (form) {
            var array = $(form).serializeArray();
            var pdata = {};
            var indexer = {};
            for (var i = 0; i < array.length; i++) {
                var index = array[i].name.indexOf('[');
                if (index != -1) {
                    //exclude invalid data
                    var isBadValue = false;
                    for (var j = 0; j < mdcs.badValues.length; j++) {
                        if (mdcs.badValues[j] == array[i].value) {
                            isBadValue = true;
                            break;
                        }
                    }
                    if (isBadValue)
                        continue;
                    var name = array[i].name.substring(0, index);
                    if (indexer[name] == undefined)
                        indexer[name] = 0;
                    else {
                        indexer[name]++;
                    }
                    name = name + '[' + indexer[name] + ']';
                    pdata[name] = array[i].value;
                }
                else {
                    //exclude select value -1 and 0
                    if ((array[i].value == '-1' || array[i].value == '0') && $('select[name=' + array[i].name + ']').length == 1) {
                        continue;
                    }
                    pdata[array[i].name] = array[i].value;
                }
            }
            return pdata;
        };

 

select option

不建议使用-1或者0来表示未选择的值,使用空字符串即可。服务端需要使用可空类型。比如 int? provinceID。没选就是没值。provinceID.HasValue就是false

 

附赠一个坑的解决办法。

看请求传了值,服务端模型就是取不到。但是从Request.Params或者Request.Forms里能取到。

请检查属性set 是否是internal set,右键自动生成的属性就这德行。导致模型属性无法绑定。

posted @ 2016-08-25 16:54  道木先生  阅读(771)  评论(0编辑  收藏  举报