Returning Json in ASP.Net MVC 1.0

06.22.10

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

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>

 

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);
}

 

To view the request use the network tab inside developer tools(F12) of your favorite  browser.