• 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,右键自动生成的属性就这德行。导致模型属性无法绑定。

  • 相关阅读:
    python之高阶函数
    [第二版]多线程的发送与接收
    基本函数与结构
    unp.h
    gdb调试命令
    System V共享内存区
    Posix 共享内存区
    System V信号量
    Posix 信号量
    记录锁
  • 原文地址:https://www.cnblogs.com/mrtiny/p/5807489.html
Copyright © 2020-2023  润新知