asp.net MVC using ajax submit parameter matching problem solving approach _ajax related

Source: Internet
Author: User
Tags closure
Think in asp.net mvc if you use Ajax to pass parameters to the server, if the argument is a class or array (or list collection) and more complex objects, the server will always be out of value, of course, there are many examples of solutions on the web, but are all in the service side to find ways to solve (such as converting JSON to Word String, and then deserializing it into an object at the server, why not get this problem done on the client side.

The problem is not that complicated, because when you submit the array data in jquery, the submission always adds "[]" after the name, which is the problem. In addition, when parsing the array and embedded JS objects in the server, it takes a format like this, such as an array (or a list collection) to be required on the server ({' xxx[0] ': ' AAA ', ' xxx[1] ': ' BBB '} format, and the inline object needs to be like this {' xxx.a ': ' DDD ', ' xxx.b ': ' HHH '}, find out the cause of the problem is solved, if we can convert the format of JSON to the service side of the format can be recognized, the problem is not solved.

Just do it, go straight to the code.
Copy Code code as follows:

For MVC parameter fit JavaScript closure function
/*
The use of the following methods:
$.ajax ({
URL: "@Url. Action (" Ajaxtest ")",
Data:mvcparammatch ("", senddata),//In this transform JSON format, for MVC parameter submission
DataType: "JSON",
Type: "Post",
Success:function (Result) {
Alert (result. message);
}
});
*/
var Mvcparammatch = (function () {
var mvcparameteradaptive = {};
Verify that the array is being set
Mvcparameteradaptive.isarray = Function.isarray | | Function (o) {
return typeof o = = "Object" &&
Object.prototype.toString.call (o) = = "[Object Array]";
};
Convert an array to an object
Mvcparameteradaptive.convertarraytoobject = function (////////////* Array name */arrname,//* To be converted array */array,/* converted object without input */SAVEOJB) {
var obj = SAVEOJB | | {};
function func (name, arr) {
for (var i in arr) {
if (! Mvcparameteradaptive.isarray (Arr[i]) && typeof arr[i] = = = "Object") {
for (Var j in Arr[i]) {
if (Mvcparameteradaptive.isarray (Arr[i][j])) {
Func (name + "[+ i +"]. "+ j, Arr[i][j]);
else if (typeof arr[i][j] = = "Object") {
Mvcparameteradaptive.convertobject (name + "[+ i +"]. "+ j +". ", Arr[i][j], obj);
} else {
Obj[name + "[" + i + "]." + j] = Arr[i][j];
}
}
} else {
Obj[name + "[" + i + "]"] = Arr[i];
}
}
}
Func (arrname, array);
return obj;
};
Converting objects
Mvcparameteradaptive.convertobject = function (/* Object name */objname,/* object to be converted */turnobj,//* converted object without input */SAVEOJB) {
var obj = SAVEOJB | | {};
function func (name, tobj) {
for (var i in tobj) {
if (Mvcparameteradaptive.isarray (Tobj[i])) {
Mvcparameteradaptive.convertarraytoobject (i, tobj[i], obj);
else if (typeof tobj[i] = = "Object") {
Func (name + i + ".", Tobj[i]);
} else {
Obj[name + i] = tobj[i];
}
}
}
Func (objname, turnobj);
return obj;
};
return function (JSON, arrname) {
Arrname = Arrname | | "";
if (typeof JSON!== "Object") throw new Error ("Please pass in the JSON object");
if (Mvcparameteradaptive.isarray (JSON) &&!arrname) throw new Error ("Please specify an array name, corresponding to the array parameter name in the action!") ");
if (Mvcparameteradaptive.isarray (JSON)) {
Return Mvcparameteradaptive.convertarraytoobject (Arrname, JSON);
}
Return Mvcparameteradaptive.convertobject ("", JSON);
};
})();

The use of the method is very simple, look at the following example:
First is the client's code
Copy code code as follows:

var senddata = {
"Comment": "QQQ",
"Ajax1": {"Name": "Sq", "Age": ", ajax3s": {"Ajax3num": 234}},
"Ajax2s": [{"note]:" AAA "," Num ":" Ajax1s ": [{" Name ":" Sq1 "," Age ":" ajax3s ": {" Ajax3num ": 456}}, {" Name ":" SQ2 "," Age ":" ajax3s ": {" Ajax3num ": 789}}]},
{"Note": "BBB", "Num": The "ajax1s": [{"Name": "Sq3", "age": A, "ajax3s": {"Ajax3num": 654}}, {"Name": "Sq4", "Age" : 987}]}
};


$.ajax ({
URL: "@Url. Action (" Ajaxtest ")",
/*
This uses the closure function to convert the JSON object, if your JSON object itself is a array of arrays,
Then you need to specify a name that corresponds to the name of the array parameter in the action like this
Data:mvcparammatch (senddata, "parameter name corresponding to action")
*/
Data:mvcparammatch (SendData),
DataType: "JSON",
Type: "Post",
Success:function (Result) {
Alert (result. message);
},
Error:function (a,b,c) {
}
});

Then the client-side JSON entity class for the server
Copy Code code as follows:

public class Ajaxparammodels
{
public string Comment {set;
Public Ajax1 Ajax1 {set; get;}
Public list<ajax2> ajax2s {set; get;}
}
public class Ajax1
{
public string Name {set;
public int Age {set;
Public Ajax3 ajax3s {set; get;}
}
public class Ajax2
{
public string Note {set;
public int Num {set;
Public list<ajax1> ajax1s {set; get;}
}
public class Ajax3
{
public int Ajax3num {set; get;}
}

And then the action code in the controller.
Copy Code code as follows:

public class Testcontroller:controller
{
//
Get:/test/
Public ActionResult Index ()
{
return View ();
}
Public ActionResult Ajaxtest (Models.ajaxparammodels model)
{
Here you can access model
Return Json (New {message = "QQQQQ"});
}
}

That's OK, no matter how much complexity you have with the JSON object, he will automatically switch to the format that the server requires, and the server doesn't have to worry anymore.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.