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" ; 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){}