JSON Binding Support to Post Array Object with ViewModel in ASP.NET MVC 3

In JSON Binding Support to Post Action Method with ViewModel in ASP.NET MVC 3, I explained how to take advantage of JSON Binding Support in ASP.NET MVC 3 to post ViewModel object to the Controller. This post will extend the original post to allow posting of multiple objects.

I will use the same ViewModel as in the original post with the addition of the following object, which basically contains list of Person object:

public class Persons
{
    public List<Person> PersonList { get; set; }
}

The Controller will be pretty much the same as the original post, with the exception of the parameter:

[HttpPost]
public ActionResult SubmitMultiplePostObjectsInJsonWithViewModel(Development.MvcApp.Models.Persons objectsModel)
{
    return View(objectsModel);
}

This will allow the Controller to receive multiple Person objects as Persons ViewModel.

Here’s the JSON object I sent to the Controller:

{ "PersonList": [{ "Firstname": "testFirstname1", "Lastname": "testLastname1", "Email": "testEmail1", "PhoneNumber": "testNumber1" }, { "Firstname": "testFirstname2", "Lastname": "testLastname2", "Email": "testEmail2", "PhoneNumber": "testNumber2"}] }

The request:

The response:

Few important notes:

  1. The ViewModel object’s properties (“PersonList”) must match JSON object’s string.
  2. The ViewModel object’s properties must have “{ get; set; }”.
  3. The request’s Content Type must be “application/json”.

3 thoughts on “JSON Binding Support to Post Array Object with ViewModel in ASP.NET MVC 3”

  1. Nice post!!
    Can you tell me the difference between poster post method and jquery post methdo?
    The same json that works fine from Poster is not working from the jquery script in my view
    Thanks!

    1. Rodrigo Juarez

      The reason is that you need to write the json like i have written below
      $.ajax({
      type: “POST”,
      async: false,
      contentType: ‘application/json’,
      url: “MethodName/”,
      data: JSON.stringify(Person),
      dataType: “json”,
      error: function (xhr, ajaxOptions, thrownError) {
      alert(thrownError);
      },
      success: function (data) {

      }
      });

Leave a comment