Dear reader of Juri's TechBlog,
I moved my blog to a new domain and a new hosting solution as well. I'm now blogging on juristr.com.

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.

Posts you might also be interested in..

Credits: Hoctro | Jack Book

3 Comments:

Peter Gfader said...

Hi Juri

Why are you using ".ajax" and not ".post"?

".post" is smart enough to recognize dataType and looks a little bit neater ;-)

http://api.jquery.com/jQuery.post/

Juri Strumpflohner said...

Sure, I took the jQuery command out of a larger context where I potentially execute a POST/GET/... depending on the executed JavaScript function.

But you're right, in this sample I should have used directly POST :) thx for the hint.

Lava Infotech said...

Web Application Development.
This is really interesting, You’re a very skilled blogger. I have joined your feed and stay up for in the hunt for extra of your fantastic post. Also, I have shared your website in my social networks.

Post a Comment