JSON Binding Support to Post Action Method with ViewModel in ASP.NET MVC 3

ViewModel object is very good solution for form posting when used within internal application. But, what if your ASP.NET MVC application needs to communicate with outside world? There’s JSON Binding Support in ASP.NET MVC 3.

The best part is, ViewModel object can still be used in this approach.

Controller to process post back:

[HttpPost]
public ActionResult SubmitPostObject(Development.MvcApp.Models.Person objectModel)
{
    return Json(objectModel);
}

The ViewModel:

public class Person
{
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public string Email { get; set; }
    public string PhoneNumber { get; set; }
}

To test this, I will use Poster, an add-on for Mozilla Firefox.

As you can see, I specify the following Json object to be sent to the Controller:

{ "Firstname": "Alexander", "Lastname": "Witt", "Email": "awitt@gmail.com", "PhoneNumber": "(756) 847-7236" }

For simple demonstration purpose, the Controller only returns Json object pass to it. Here’s the response from Poster:

Obviously, you can also specify your Controller to return any type of result object.

Few important things to note:

  1. This is new feature in ASP.NET MVC 3 (See “JavaScript and AJAX Improvements“).
  2. The JSON object’s strings (‘Firstname’, ‘Lastname’, ‘Email’, and ‘PhoneNumber’) must match ViewModel object’s properties.
  3. ViewModel object’s properties must have “{ get; set; }” method.
  4. Must specify Content Type as “application/json” in the request.
  5. If it’s still not working, check the JSON string to make sure it’s valid one.

7 thoughts on “JSON Binding Support to Post Action Method with ViewModel in ASP.NET MVC 3”

  1. How long did it acquire you to write “JSON Binding Support to Post Action Method with
    ViewModel in ASP.NET MVC 3 | Stack 24/7”?

    It possesses quite a lot of beneficial information and facts.
    With thanks ,Darren

  2. If you would like to increase your know-how
    only keep visiting this site and be updated with the hottest gossip posted here.

Leave a comment