當用$.ajax()向後臺提交參數時,若是參數中數組的話通常在後臺會用List<T>接收;但總是不成功以下面代碼
jquery
var arr1=[{ "aa": "1", "bb": "2" }, { "aa": "3", "bb": "4"}]; var arr2=[{ "aa": "1", "bb": "2" }, { "aa": "3", "bb": "4"}]; function addUser(){ $.ajax({ url:'UserAdd', data:{list1:arr1,list2:arr2}, type:'post', success:function(msg){ if(msg=='1'){ console.log('添加成功'); }else{ console.log('添加失敗') } } }); }
用Fiddler 監測以後發覺數據變成啦ajax
list1[0][aa]=1&list1[0][bb]=2&list1[1][aa]=3&list1[1][bb]=4&list2[0][aa]=1&list2[0][bb]=2&list2[1][aa]=3&list2[1][bb]=4
C#中能識別的數組應該是這樣的格式json
list1[0].aa=1&list1[0].bb=2&list1[1].aa=3&list1[1].bb=4&list2[0].aa=1&list2[0].bb=2&list2[1].aa=3&list2[1].bb=4
在網上查找資料以後瞭解到ajax post以前會用由於jQuery須要調用jQuery.param序列化參數,咱們來看下jquery源碼數組
//在ajax()方法中,對json類型的數據進行了$.param()處理 if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } //param方法中 if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } }
找到緣由以後就好辦啦post
首先,traditional爲false,咱們能夠經過設置traditional 爲true阻止深度序列化ui
先寫一個數組轉爲對象的方法:this
Array.prototype.serializeObject = function (lName) { var o = {}; $t = this; for (var i = 0; i < $t.length; i++) { for (var item in $t[i]) { o[lName+'[' + i + '].' + item.toString()] = $t[i][item].toString(); } } return o; };
var arr1=[{ "aa": "1", "bb": "2" }, { "aa": "3", "bb": "4"}]; var arr2=[{ "aa": "1", "bb": "2" }, { "aa": "3", "bb": "4"}]; function addUser(){ $.ajax({ url:'UserAdd', data:$.param(arr1.serializeObject("list1"))+"&"+$.param(arr2.serializeObject("list2"), //手動把數據轉換拼接 type:'post', traditional:true, //這裏必須設置 success:function(msg){ if(msg=='1'){ console.log('添加成功'); }else{ console.log('添加失敗') } } }); }
C#後臺接收代碼url
public class Test { public int aa{ get; set; } public int bb{ get; set; } } public ActionResult UserAdd( List<Test> list1, List<Test> list2) { return Json(amm); }
這樣一來問題就解決啦!spa