Returning Json in ASP.Net MVC

06.22.10

Problem: You want to return a Json object to your page using ASP.Net MVC.

Solution: Use JQuery.getJSON and JsonActionResult.

CODE:

View HTML

<ul id="jsonRequestFun">
</ul>
<a href="#" id="requestFun">Json is fun</a>

View Javascript

<script type="text/javascript">
$(function () {
$("#requestFun").click(function () {
$.getJSON("/home/jsonfun", null, function (data) {
$("<li>" + data.Message + "</li>").appendTo("#jsonRequestFun");
$("<li>" + data.Time + "</li>").appendTo("#jsonRequestFun");
});
});
});
</script>

Handy tool to view the request in IE is nikhilk.net Web development Helper

Once installed the tool is a bit hidden you can find it at Tools>Explorer Bars>Web Developer Helper

openDevHelper

Enable Logging to view the request.

webdevhelper

Model:

public class JsonData
{
public string Message { get; set; }

public string Time { get; set; }
}

 

Controller Action:

Beware of this little gotcha if you do not pass the AllowGet your requests will be ignored.

public ActionResult JsonFun()
{
var data = new JsonData
{
Message = "Hello World",
Time = DateTime.Now.ToShortTimeString()
};
return Json(data, JsonRequestBehavior.AllowGet);
}