RSS

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

20 Mar

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.
About these ads
 
5 Comments

Posted by on March 20, 2011 in General

 

Tags: , , ,

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

  1. http://tinyurl.com/clerrees23171

    February 6, 2013 at 4:11 am

    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. Read this

    April 29, 2013 at 1:22 am

    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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

Join 38 other followers

%d bloggers like this: