且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.NET MVC 4 JSON 绑定到视图模型 - 嵌套对象错误

更新时间:2023-02-25 18:26:51

问题出在你的action方法参数上:

The problem is from your action method parameter:

[HttpPost]
public ActionResult SaveAddress(AddressViewModel addressViewModel)

当您使用 JSON.stringify() 时,您向控制器发送了一个字符串,而不是一个对象!所以,你需要做一些工作来实现你的目标:

As you use JSON.stringify(), you send a string to your controller, not an object! So, you need to do some works to achive your goal:

1) 更改您的操作方法参数:

1) Change your action method parametter:

[HttpPost]
public ActionResult SaveAddress(string addressViewModel)

2) 将该字符串反序列化为一个对象 - 即 AddressViewModel:

2) Deserialize that string to an object - that is AddressViewModel:

IList<AddressViewModel> modelObj = new 
JavaScriptSerializer().Deserialize<IList<AddressViewModel>>(addressViewModel);

因此,您的最终操作方法应如下所示:

So, your final action method should be like the following:

[HttpPost]
public ActionResult SaveAddress(string addressViewModel)
{
    IList<AddressViewModel> modelObj = new 
    JavaScriptSerializer().Deserialize<IList<AddressViewModel>>(addressViewModel);

    // do what you want with your model object ...
}