Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning JsonResult results in 500 Internal Server Error

I'm using jQuery's getJSON function to return a JsonResult from my controller.

jQuery

$.getJSON("/Test/GetJsonWFA", null, function (data) {
    $(data).each(function () {
        alert("call succeeded");
        //alert(data);
    });
});

controller

public JsonResult GetJsonWFA() 
{
    List<WorkFlowAssignment> listWFAs = new List<WorkFlowAssignment>();

    listWFAs.Add(new WorkFlowAssignment() 
    { 
        ID = 1, 
        WorkFlowName = "WorkFlowName1" 
    });

    listWFAs.Add(new WorkFlowAssignment() 
    { 
        ID = 2, 
        WorkFlowName = "WorkFlowName2" 
    });

    return Json(listWFAs, JsonRequestBehavior.AllowGet);
}

I'm getting the following error: 500 Internal Server Error.

If I replace the WorkFlowAssignment in GetJsonWFA with a trivial class everything works.

It seems to be related to the type of object in the list.

The WorkFlowAssignment class has many properties and methods.

Can anyone point me in the right direction?

like image 359
Derek Mitchell Avatar asked Nov 06 '11 12:11

Derek Mitchell


1 Answers

I suspect that your WorkFlowAssignment model has some circular references which cannot be JSON serialized. I would recommend you to use a view model and break any possible circular references. Another advantage of using a view model is that you will send to the client only the properties it actually needs in order to do the processing. You don't need to transfer over the wire some complex stuff that the client will never need. So for example if everything that your client needs is the ID and the WorkFlowName do this:

public ActionResult GetJsonWFA() {
    List<WorkFlowAssignment> listWFAs = ... 

    var viewModel = listWFAs.Select(x => new {
        ID = x.ID,
        WorkFlowName = x.WorkFlowName
    });
    return Json(viewModel, JsonRequestBehavior.AllowGet);
}

and on the client:

$.getJSON("/Test/GetJsonWFA", null, function (data) {
    $.each(data, function (index, item) {
        alert('ID = ' + item.ID + ', WorkFlowName = ' + item.WorkFlowName);
    });
});

Also you should use debugging tools such as FireBug or Developer Toolbar to inspect the AJAX request that your browser sends and analyze the server response for eventual errors. When an AJAX request fails your first reaction as a developer should be to launch your debugging tool and see exactly what request/response is being sent.

like image 70
Darin Dimitrov Avatar answered Sep 22 '22 18:09

Darin Dimitrov