且构网

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

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

更新时间:2023-02-25 18:48:15

问题是从你的行动方法的参数:

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)改变你的操作方法parametter:

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 ...
}