.NET

Posting JSON Data to an ASP.net MVC 3 Web Application

The trend in today’s web application development goes more and more in the direction of having rich, desktop-like applications. There are numerous examples on the web, just watch out while your navigating around (Google services are always a good place to look for such apps).

But also Microsoft has noted that trend and aligns its products in order reduce the pain to code such rich ajax apps to the minimum possible. A good example is ASP.net MVC 3. Below is a quick example on how easy it is to establish a data exchange mechanism between a JavaScript web app and an ASP.net MVC 3 web application. In the example I use JSON as the data exchange format as it is most convenient in a JavaScript environment and moreover it tends to be more compact than other formats (i.e. like XML).


Assume to have the following model on the server-side:

public class Person
{
    public long Id { get; set; }
    public string Firstname { get; set; }
    public string Surname { get; set; }
    public int Age { get; set; }
    public Address Address { get; set; }
}
public class Address
{
    public string Street { get; set; }
    public string Cap { get; set; }
    public string City { get; set; }
}

I create a controller that handles a CRUD operation for a Person object.

public class PersonController : Controller
{
   [HttpPost]
   public JsonResult Create(Person person)
   {
      return Json(person); //dummy example, just serialize back the received Person object
   }
}

Note, the JsonResult return type, but most importantly, note the signature of the Create method. Beside the HttpPost it looks like a plain normal method, right? This method is now accessible through the uri /person/create.

On the client-side there is a rich JavaScript app, and somewhere a piece of code that posts the data to the server:

var samplePersonObject = {
   firstname: "Juri",
   surname: "Strumpflohner",
   address: {
      street: "Via ....",
      cap: "39100",
      city: "Bolzano (BZ)"
   }
};
var jsonSerialized = JSON.stringify(samplePersonObject);
$.ajax({
   type: "POST",
   url: "/person/create",
   dataType: "json",
   contentType: "application/json; charset=utf-8",
   data: jsonData,
   success: function (result){
      console.log(result); //log to the console to see whether it worked
   },
   error: function (error){
      alert("There was an error posting the data to the server: " + error.responseText);
   }
});

The highlighted lines are the most important ones. These have to match with the kind of return and parameter type the Action method on your ASP.net MVC controller assumes.

Some blogs specify the necessity of explicitly registering a JsonValueProviderFactory on your application start like

protected void Application_Start()
{
   ...
   ValueProviderFactories.Factories.add(new JsonValueProviderFactory());
}

On my setup this wasn’t necessary as the JsonValueProviderFactory was already registered by default. I didn’t verify that in more detail, though.

I really like the simplicity of how the communication is established. There is no boilerplate code on the server that maps raw Http request data to the specific server-side entity of interest (although you could also accept a generic FormCollection type). Your JSON object’s properties need simply to match the server-side entity’s property names.


References: Posting JSON Data to an ASP.net MVC 3 Web Application  from our NCG partner Juri Strumpflohner at the Juri Strumpflohner’s TechBlog blog.

Related Articles

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
disqus_eCTIKYdO7c
disqus_eCTIKYdO7c
11 years ago

OW

Back to top button