When a parameter is submitted to the background with $.ajax (), the array in the argument is usually received in the background by list<t>, but it is always unsuccessful as the following code
vararr1=[{"AA":"1","BB":"2"}, {"AA":"3","BB":"4"}];vararr2=[{"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 ('Add Success'); }Else{Console.log ('Add failed') } } }); }
After monitoring with fiddler, the data becomes
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
The array that can be recognized in C # should be in this format
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
After looking at the information on the web and knowing that Ajax post would be used because jquery needs to call Jquery.param serialization parameters, let's look at the jquery source
//In the Ajax () method, the JSON-type data is $.param () processedif(S.data && S.processdata &&typeofS.data!== "string") {S.data=Jquery.param (S.data, s.traditional);}//in the Param methodif(Jquery.isarray (a) | | (A.jquery &&!)Jquery.isplainobject (a))) { //Serialize the form elementsJquery.each (A,function() {Add ( This. Name, This. Value); }); } Else { //If Traditional, encode the "old" (the 1.3.2 or older //Did it), otherwise encode params recursively. for(Prefixincha) {buildparams (prefix, a[prefix], traditional, add); } }
I'll do it after I find out why.
First, traditional is false, we can prevent deep serialization by setting traditional to True
First, write an array to the object method:
Array.prototype.serializeObject = function (lName) { var o = = this for (var i = 0; i < $t. length; i++ for (var Item in $t [i]) {o[l Name + ' [' + i + ']. ' + item.tostring ()] = $t [I][item].tostring (); }} return o; };
vararr1=[{"AA": "1", "BB": "2"}, {"AA": "3", "BB": "4"}];vararr2=[{"AA": "1", "BB": "2"}, {"AA": "3", "BB": "4"}];functionAddUser () {$.ajax ({URL:' UserAdd ', Data:$.param (Arr1.serializeobject ("List1") + "&" +$.param (Arr2.serializeobject ("List2"),//manually turn data into stitchingType: ' Post ', Traditional:true,//This must be setSuccessfunction(msg) {if(msg== ' 1 ') {Console.log (' Add success '); }Else{Console.log (' Add failed ') } } }); }
C # background receive code
Public class Test { publicintgetset;} Public int Get Set ; } } Public ActionResult UserAdd (list<test> list1, list<test> list2) { return Json (AMM); }
So the problem is solved!
JQuery's Ajax method commits multiple object array problems C # traditional $.param