Posting JSON Data to an ASP.net MVC 3 Web Application
3 min read
3 min read
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 PersonI create a controller that handles a CRUD operation for a
{
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; }
}
Person
object.public class PersonController : ControllerNote, the
{
[HttpPost]
public JsonResult Create(Person person)
{
return Json(person); //dummy example, just serialize back the received Person object
}
}
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
.var samplePersonObject = {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.
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: jsonSerialized,
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);
}
});
protected void Application_Start()On my setup this wasn't necessary as the JsonValueProviderFactory was already registered by default. I didn't verify that in more detail, though.
{
...
ValueProviderFactories.Factories.add(new JsonValueProviderFactory());
}