Rendering JSON Data in MVC Asp.Net [Example]

Leave a Comment
JavaScript Object Notation (JSON) is a simple and very effective format for transmitting data over the Web. JSON objects leverage two types of data structures to represent data: collections of name/value pairs, and ordered lists of values (aka arrays). And, as its name implies, JavaScript Object Notation is based on a subset of the JavaScript language, so all modern browsers already understand it.

ASP.NET MVC offers native JSON support in the form of the JsonResult action result, which accepts a model object that it serializes into the JSON format. In order to add AJAX support to your controller actions via JSON, simply use the Controller.Json() method to create a new JsonResult containing the object to be serialized.

To show the Json() helper and JsonResult in action, let’s add a JsonAuction action to the AuctionsController:

public ActionResult JsonAuction(long id)
{
var db = new DataContext();
var auction = db.Auctions.Find(id);
return Json(auction, JsonRequestBehavior.AllowGet);
}


This new controller action responds to requests with the JSON-serialized version of the auction data. For example:

{
"Title": "XBOX 360",
"Description": "Brand new XBOX 360 console",
"StartTime": "01/12/2012 12:00 AM",
"EndTime": "01/31/2012 12:00 AM",
"CurrentPrice": "$199.99",
"Bids": [
{
"Amount" : "$200.00",
"Timestamp": "01/12/2012 6:00 AM"
},
{
"Amount" : "$205.00",
"Timestamp": "01/14/2012 8:00 AM"
},
{
"Amount" : "$210.00",
"Timestamp": "01/15/2012 12:32 PM"
}
]
}


This snippet is a great example of JSON’s simplicity and elegance - notice how [ and ] define arrays and how property values can be simple data types or complex data types represented by JSON objects themselves.

0 comments:

Post a Comment