Seth Spearman Seth Spearman - 1 month ago 5
C# Question

What is the use case for using a JsonResult action in mvc3?

When is it typical to use the JsonResult action in a mvc 3 application?

From where is the JsonResult usually called? Another action or an actionlink rendered in the html?

Can you give me some examples where you want json instead of a typical view?


Say, for example you wanted to populate a jQuery autocomplete with a list of values based on a selection of another field, so you can't determine the data on page load. I would typically call an action method in a $.ajax call, then return an array of items to populate the autocomplete with.

Example, here's my jQuery, one function for the call and another that gets called to populate the automcomplete with received data:

$(function() {
            url: '@Url.Action("GetHomes", "Account")',
            type: "POST",
            datatype: "json",
            success: function (data) {
                if (data.Success || data.Success == null) {
                } else {


function WireUpHomesData(data) {
    var homes = new Array();

    for (var i = 0; i < data.length; i++) {
        homes[i] = { label: data[i].HomeName, text: data[i].HomeId, icon: data[i].HomeIcon, desc:data[i].HomeAddress };
            source: homes,
            select: function (event, item) {
                homeUrl = '@Url.Action("Site", "Sites")/' + item.item.text;
        }).data("autocomplete")._renderItem = function (ul, item) {
        return $("<li></li>")
            .data("item.autocomplete", item)
            .append("<a><span class='" + item.icon + "'/><span class='fs-ui-autocomplete-home'>" + item.value + "</span><br>" + item.desc+ "</a>")

And here is my controller:

public JsonResult GetHomes()
    return Json(RequiresAclAttribute.HomesForUser());

And here's the method signature for the method that's called:

public IEnumerable<HomeInfo> HomesForUser()

And for clarity, here's the HomeInfo class:

public class HomeInfo
    public string HomeId { get; set; }
    public string HomeName { get; set; }
    public string DisplayName { get; set; }
    public string HomeAddress { get; set; }
    public string HomeIcon { get; set; }