I’m trying to use .Net’s Ajax.BeginForm to submit a form and get back a list of objects.
@using (Ajax.BeginForm("ValidateEmployee", new AjaxOptions { OnBegin = "onBegin", OnSuccess = "onSucess", UpdateTargetId = "results"} )
Problem is, when my controller returns a JsonResult and I convert my returned list to json, the OnSuccess callback is never called and my div with id “results” is not updated. But the onBegin callback is called. The controller looks like this.
public JsonResult ValidateEmployee(Employee emp)
{
...
List<Role> roles = new Role();
foreach(var x in myCollection)
{
roles.Add(new Role { ID = x.ID, Name = x.Name });
}
return Json(roles);
}
I’ve confirmed that Json(roles) does correctly convert the list into valid json. But I can’t use it because onSuccess never runs.
Strangely, if I don’t convert the list to json and just return it as a .Net list, both callbacks are hit and my element to update outputs System.Collections.Generic.List’1[Models.Role]. So it’s not json and I don’t have a way to use the data.
So why is onSuccess not being called when I return a json object from my controller?
I’m using MVC 3 and I’m referencing jquery.unobtrusive-ajax.js.
Thanks for any help.
I don’t think you can use
Ajax.BeginFormwithUpdateTargetIdfor your scenario as you are usingJsonResultas the result of the action.Ajax.BeginForm, givenUpdateTargetIdwill try to append the resulting object to the element that you have specified. Since the returning is Json object it throws an error. The error will be something like:Once
UpdateTargetIdremoved you should see the onSuccess being fired.