Returning JsonResult results in 500 internal server errors

I am using the jQuery getJSON function to return JsonResult from my controller page.

Here is the jQuery code on the web page:

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

And here is the controller code:

  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 get the following error: Internal server error .

If you replace WorkFlowAssignment on GetJsonWFA with a trivial class, everything will work.

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

The WorkFlowAssignment class has many properties and methods.

Can someone point me in the right direction?

+4
source share
1 answer

I suspect your WorkFlowAssignment model has some circular references that cannot be serialized by JSON. I would recommend that you use the view model and break any possible circular links. Another advantage of using a view model is that you only send the client the properties that it really needs to complete the processing. You do not need to transfer to the wire any complex material that the client will never need. For example, if all your client needs is an ID and WorkFlowName to 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); }); }); 

You should also use debugging tools such as FireBug or the developer toolbar to check the AJAX request that your browser sends and analyzes the serverโ€™s response for possible errors. When an AJAX request fails, your first reaction as a developer should be to start the debugging tool and see exactly what request / response is being sent.

+12
source

Source: https://habr.com/ru/post/1379860/


All Articles