arrName = arrName || "";
if (typeof json !== "object") throw new Error("请传入json对象");
if (MvcParameterAdaptive.isArray(json) && !arrName) throw new Error("请指定数组名,对应Action中数组参数名称!");
if (MvcParameterAdaptive.isArray(json)) {
return MvcParameterAdaptive.convertArrayToObject(arrName, json);
}
return MvcParameterAdaptive.convertObject("", json);
};
})();
使用方法非常简单,看下面的例子:
首先是客户端的代码
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")",
/*
在此使用闭包函数转换json对象,如果你的json对象自身就是个数组Array,
那么需要指定一个名称,这个名称对应于Action中这个数组参数的名称像这样
data:mvcParamMatch(sendData,"Action中所对应的参数名称")
*/
data: mvcParamMatch(sendData),
dataType: "json",
type: "post",
success:function(result) {
alert(result.Message);
},
error:function(a,b,c) {
}
});
然后是服务端对应客户端json的实体类
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; }
}
然后是controller中的action代码
public class TestController : Controller
{
//
// GET: /Test/
public ActionResult Index()
{
return View();
}
public ActionResult AjaxTest(Models.AjaxParamModels model)
{
//在此可访问model
return Json(new {Message = "qqqqq"});
}
}
这样就OK了,不管你这个json对象有多少复杂都没关系,他会自动转换为服务端要求的格式,服务端再也不用操心了。









