ASP.NET MVC 4 JSON Binding to the View Model - Nested object error ASP.NET MVC 4 JSON Binding to the View Model - Nested object error json json

ASP.NET MVC 4 JSON Binding to the View Model - Nested object error


You can keep your existing ActionMethod untouched without the need of json serializing:In the client side create an object from your json:

JSON.parse(jsonData)

and send that in the $.ajax data property.

Or, instead of creating json, create an object:

var dataObject = new Object();dataObject.Town = $('#txt-Town').val();dataObject.District = $('#txt-District').val();...

And again, send that object in the $.ajax data property.


The problem is from your action method parameter:

[HttpPost]public ActionResult SaveAddress(AddressViewModel addressViewModel)

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) Change your action method parametter:

[HttpPost]public ActionResult SaveAddress(string 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 ...}


Actually the best option is just to remove the

var addressData = JSON.stringify(jsonData);

line and send jsonData itself. ASP.NET MVC will auto-bind it if it is an actual object and not just a string.

Occam's Razor