Schubert's Blog

A biker and technology enthusiast's
view of the world

Returning JSON result in ASP.Net MVC 2

One ASP.Net MVC feature that I discovered and took full advantage of, whilst building Mapze.com Beta 2 was the ease with which JSON result could be returned for a web request.

It is as simple as calling the JSON function from the inherited Mvc.Controller class. The first parameter is the object or list of objects you would like to return in your JSON result. The second parameter is optional, but I had to set it to JsonRequestBehavior.AllowGet. This is because of the way GET request are secured in ASP.Net MVC 2. My final server side code to return events using JSON looked like:

//The parameters are as following:
//mo = mode, this can be 3 or 10. 3 returns short descriptions for the top 3 events,
// 10 returns a more detailed description of the first 10 events and supports paging
//y = year the user would like to find event in
//m = month
//d = day
//ctry = country
//reg = region
//cty = city
//pg = page number, this is obtained via the requested query string in code

public ActionResult GetJson(int mo, int y, int m, int d, string ctry,
string reg, string cty)
{
//Taking care of paging request
int pageNo = 0;
if (mo != 10)
{
//If the mode is not 10, set page number to 0
pageNo = 0;
}
else
{
//Getting page number from the requested query string
// and setting it to a safe value for later use
if (int.TryParse(Request.QueryString.Get("pg"), out pageNo))
pageNo = pageNo > 0 ? pageNo - 1 : 0;
}

//Create an instance of the Business logic class
BlEvents = new BlEvents();

//Returning JSON results based on the mode
switch(mo)
{
case 10:
var shortResults = BlEvents.GetTop3Events(y, m, d, ctry, reg, cty);
return Json(shortResults, JsonRequestBehavior.AllowGet);
//break;
case 3:
default:
var extResults = BlEvents.GetPagedEvents(y, m, d, ctry, reg, cty, pageNo);
return Json(extResults, JsonRequestBehavior.AllowGet);
//break;
}
}

The end result, two types of JSON results. The first url return the top 3 events with a short description for the 23 of August 2010 and the second url returns the top 10 events with a longer description and other fields for the 31 of September 2010. The last entry always has the Id set to 0, the Title to "Powered by Mapze.com". And the short description is set to the number of events that Mapze.com has for that date, useful for other website and users to making paged JSON request.

http://www.mapze.com/event/getjson/3/2010/5/23

http://www.mapze.com/event/getjson/10/2010/10/31

In the previous blog entry, I've discuss using TSQL with no lock. An insight I've used to performance tune the TSQL queries behind these JSON calls. In a future blog, I'll discusses how I've use JQuery to request and present these JSON reponses in the browser.

By Schubert on 03 January 2011 12:42

Categories: Development | Tags: , , , ,

Permalink | Comments (0)

Submit to DotNetKicks...