Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
139
rated 0 times [  145] [ 6]  / answers: 1 / hits: 20284  / 13 Years ago, sun, november 6, 2011, 12:00:00

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?


More From » jquery

 Answers
18

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.


[#89281] Thursday, November 3, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aubriea

Total Points: 641
Total Questions: 118
Total Answers: 101

Location: French Southern and Antarctic Lands
Member since Fri, Jan 6, 2023
1 Year ago
;