我使用手动序列化/反序列化对我的控制器操作进行了示例 jquery 调用。我可以很好地来回发送一个复杂的对象。但是使用“自动”反序列化的相同代码仅发送对象的外部部分,但内部为空。
这是一个错误吗?..我认为太大了,我应该配置一些东西来告诉 MVC“请按预期做”吗?这是我的有效代码,我的无效代码。
有效的代码: Javascript: var modelListData = { "listname": "xname", "samplemodels": [{ "name": "pepe1" }, { "name": "pepe2" }, { "name": "pepe3 " }, { "name": "pepe4" }]};
$.ajax({
url: "http://localhost:1629/Sample/MyTestMethod5",
method: 'POST',
data: { "sampleModelListJson": JSON.stringify(modelListData) },
success: processGetJSONList,
error: function (data) { alert("error" + data); }
});
控制器动作:
public ActionResult MyTestMethod5(string sampleModelListJson)
{
SampleModelList inputModelList = JsonConvert.DeserializeObject<SampleModelList>(sampleModelListJson);
SampleModelList outputModelList = new SampleModelList();
outputModelList.listname = inputModelList.listname + "xxx";
outputModelList.samplemodels = inputModelList.samplemodels;
return Json(outputModelList, JsonRequestBehavior.AllowGet);
}
不起作用的代码:
Javascript:
$.ajax({
url: "http://localhost:1629/Sample/MyTestMethod6",
method: 'POST',
data: modelListData, //reusing previous one
success: processGetJSONList,
error: function (data) { alert("error" + data); }
});
控制器动作:
public ActionResult MyTestMethod6(SampleModelList sampleModelList)
{
SampleModelList outputModelList = new SampleModelList();
outputModelList.listname = sampleModelList.listname + "xxx";
outputModelList.samplemodels = sampleModelList.samplemodels;
return Json(outputModelList, JsonRequestBehavior.AllowGet);
}