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

JSON Binding Support is only available in ASP.NET MVC 3. However, there is a workaround we can do to make this work in ASP.NET MVC 2.

I will use the same ViewModel in ASP.NET MVC 3 Post.

Here’s the Controller:

public ActionResult SubmitPostObjectInJsonWithViewModel(string objectModel)
{
    System.Web.Script.Serialization.JavaScriptSerializer _jsonDeserializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    var _person = _jsonDeserializer.Deserialize(objectModel, new Development.MvcApp.Models.Person().GetType());

    return Json(_person);
}

For simple demonstration purpose, the Controller only returns Json object pass to the Controller.

As mentioned in ASP.NET MVC 3 Post, I use Poster, a Mozilla Firefox add-on to test posting to the Controller.

Here’s the request:

Here’s the response:

Basically, this approach is the same as what I described here. We take string input (which essentially is a JSON string) in our Controller and deserialize it to our ViewModel object.

Few things to note:

  1. The request must NOT be “application/json”. The request is a regular post action request.
  2. Parameter used in Controller must match the request parameter’s name.
  3. System.Web.Script.Serialization.JavaScriptSerializer is obsoleting according to Scott Gu’s post, but will still be available in few .Net versions to come.
Advertisements

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

  1. Usually I don’t read article on blogs, but I wish to say that this write-up very forced me to try and do it! Your writing style has been amazed me. Thanks, very nice post.

Leave a Reply to ajit Cancel 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