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:

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.

5 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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s