zoukankan      html  css  js  c++  java
  • mvc数组模型绑定-jquery ajax

    <script>
    var
    list=[];//数组 list[0]=1001; list[1]=1002; list[1]=1003; var json_data = { selected: list}; $.ajax({ url: '/xk/select', type: 'POST', data: json_data, success: function (j) { }, error: function () { } });
    </script>

    上述请求发出后,jquery会把json_data序列化为id=1&selected[]=1001&selected[]=1002&selected[]=1003的形式

    假如mvc的action如下,seleted始终为null

    public JsonResult select(int[] selected){}

    MVC只会把下面两种请求转换为数组:
    同名:arr=1001&arr=1002
    索引:arr[0]=1001&arr[1]=1002

    因此,jquery.ajax不能采用数组方式传递参数,可以换成对象的方式

    <script>
    var
    obj= {};//注意这里是对象,不是数组 obj[0] ="1001" ;//中括号属性设置法,等价于obj["0"]="1001"; obj[1] ="1002" ; obj[1] ="1003" ; //下面就可以发送请求了 var json_data = { selected: obj}; $.ajax({ url: '/xk/select', type: 'POST', data: json_data, success: function (j) { }, error: function () { } });
    </script>

     这种处理,请求数据变成了selected[0]=1001&selected[1]=1002&selected[2]=1003的形式,

    另外一种方式就是,ajax加traditional : true

    <script>
    var
    list= [];//注意这里是数组 list[0] ="1001" ;//中括号属性设置法,等价于student_ids["0"]="1001"; list[1] ="1002" ; list[1] ="1003" ; //下面就可以发送请求了 var json_data = { 'selected': list}; $.ajax({ url: '/xk/select', type: 'POST', data: json_data, traditional : true,//注意这里 success: function (j) { }, error: function () { } });
    </script>

     通过这种方式,请求变成了selected=1001&selected=1002&selected=1003的形式

    public JsonResult Select(int[] selected){}就可以正常接收数组selected了

    以上是简单数组绑定,下面考虑复杂对象数组绑定

    <script>

    var list= [];
    list.push( { book_name: “1”, book_version: "1","book_publication":"1","book_author":"1"});
    list.push({ book_name: “2”, book_version: "2","book_publication":"2","book_author":"2"});
    list.push({ book_name: “3”, book_version: "3","book_publication":"3","book_author":"3"});

    $.ajax({
    url: '/Book/AddBooks',
    type: 'POST',
    data: {books:list},
    success: function (j) {
    },
    error: function () {
    }
    });

    </script>

    截获的请求发现对象的属性,都自动加了中括号,导致mvc无法绑定到模型上!!

    换成对象的形式则能成功绑定

    <script>

    var list= {};//可以成功进行模型绑定
    list[0] = { book_name: “1”, book_version: "1","book_publication":"1","book_author":"1"};
    list[1] = { book_name: “2”, book_version: "2","book_publication":"2","book_author":"2"}; 
    list[2] = { book_name: “3”, book_version: "3","book_publication":"3","book_author":"3"};

    </script>

    控制器如下:

    public JsonResult AddBooks(BookInfo[] books){}



  • 相关阅读:
    Linux指令集
    [日记]贝鲁特煎熬第32天
    2019南京区域赛ABCHJK题解 & KMbfs(O(n^3))板子
    欧拉筛质数以及四大积性数论函数(欧拉函数、莫比乌斯函数、约数个数函数、约数和函数)
    简短的自我介绍
    BSTTreap名次树数组&指针实现板子 Ver1.0
    2019银川区域赛BDFGHIKN题解
    安装vs2010
    SPEmailEventReceiver 之导入附件EXCEL
    为incoming mail绑定事件,SPEmailEventReceiver
  • 原文地址:https://www.cnblogs.com/imust2008/p/7924799.html
Copyright © 2011-2022 走看看