Discussion on the matching problem of MVC submission parameters using Ajax in asp.net

Time:2021-9-5

In the MVC of asp.net, if AJAX is used to pass parameters to the server, if the parameters are a class or an array (or list collection) and more complex objects, the server will always fail to get the value. Of course, there are many solutions on the Internet, but they are all solved by the server (such as converting JSON to string), Then deserialize to an object on the server side), why can’t you solve this problem on the client side.

In fact, the problem is not so complicated, because when jQuery submits the data of array, it always adds “[]” after the name. That’s the problem. In addition, when parsing arrays and embedded JS objects on the server side, you need a format like this. For example, the array (or list set) needs such a format as {XXX [0] ‘:’aaa’, ‘xxx [1]’:’bbb ‘} on the server side, and the embedded objects need such a format as {XXX. A’:’ddd ‘,’ xxx. B ‘:’hhh’}. Find the cause of the problem, If we can convert the JSON format into a format that the server can recognize, the problem will not be solved.

Just do what you say and go straight to the code

Copy codeThe code is as follows:
//JavaScript closure function for MVC parameter adaptation
/*
The usage is as follows:
$.ajax({
url: “@Url.Action(“AjaxTest”)”,
Data: mvcparamatch (“”, SendData), / / convert JSON format here for MVC parameter submission
dataType: “json”,
type: “post”,
success:function(result) {
alert(result.Message);
}
});
*/
var mvcParamMatch = (function () {
var MvcParameterAdaptive = {};
//Verify that is an array
MvcParameterAdaptive.isArray = Function.isArray || function (o) {
return typeof o === “object” &&
Object.prototype.toString.call(o) === “[object Array]”;
};
//Convert array to object
Mvcparameteradaptive.convertarraytoobject = function (/ * array name * / arrayname, / * array to be converted * / array, / * object stored after conversion, do not enter * / 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;
};
//Conversion object
Mvcparameteradaptive.convertobject = function (/ * object name * / objname, / * object to be converted * / turnobj, / * object stored after conversion, do not enter * / 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 JSON object “);
if (MvcParameterAdaptive.isArray(json) && ! Arrname) throw new error (“please specify the array name, corresponding to the array parameter name in action!”);
if (MvcParameterAdaptive.isArray(json)) {
return MvcParameterAdaptive.convertArrayToObject(arrName, json);
}
return MvcParameterAdaptive.convertObject(“”, json);
};
})();

The use method is very simple. See the following example:
The first is the client code

Copy codeThe code is as follows:
var sendData = {
“Comment”: “qqq”,
“Ajax1”: { “Name”: “sq”, “Age”: 55, “Ajax3S”: { “Ajax3Num”: 234 } },
“Ajax2S”: [{ “Note”: “aaa”, “Num”: 12, “Ajax1S”: [{ “Name”: “sq1”, “Age”: 22, “Ajax3S”: { “Ajax3Num”: 456 } }, { “Name”: “sq2”, “Age”: 33, “Ajax3S”: { “Ajax3Num”: 789 } }] },
{ “Note”: “bbb”, “Num”: 34, “Ajax1S”: [{ “Name”: “sq3”, “Age”: 44, “Ajax3S”: { “Ajax3Num”: 654 } }, { “Name”: “sq4”, “Age”: 987 }] }]
};

$.ajax({
url: “@Url.Action(“AjaxTest”)”,
/*
Here, use the closure function to convert the JSON object. If your JSON object itself is an array,
Then you need to specify a name, which corresponds to the name of the array parameter in the action, like this
Data: mvcparammatch (SendData, “corresponding parameter name in action”)
*/
data: mvcParamMatch(sendData),
dataType: “json”,
type: “post”,
success:function(result) {
alert(result.Message);
},
error:function(a,b,c) {
}
});

Then there is the entity class of the server corresponding to the client JSON

Copy codeThe code is as follows:
public class AjaxParamModels
{
public string Comment { set; get; }
public Ajax1 Ajax1 { set; get; }
public List<Ajax2> Ajax2S { set; get; }
}
public class Ajax1
{
public string Name { set; get; }
public int Age { set; get; }
public Ajax3 Ajax3S { set; get; }
}
public class Ajax2
{
public string Note { set; get; }
public int Num { set; get; }
public List<Ajax1> Ajax1S { set; get; }
}
public class Ajax3
{
public int Ajax3Num { set; get; }
}

Then there is the action code in the controller

Copy codeThe code is as follows:
public class TestController : Controller
{
//
// GET: /Test/
public ActionResult Index()
{
return View();
}
public ActionResult AjaxTest(Models.AjaxParamModels model)
{
//Here you can access the model
return Json(new {Message = “qqqqq”});
}
}

This is OK. It doesn’t matter how complex your JSON object is. It will automatically convert to the format required by the server, and the server won’t have to worry about it anymore.