调用返回JsonResult的操作的MVC Ajax.BeginForm在客户端上不成功

nth*_*xel 2 ajax.beginform jsonresult asp.net-mvc-3

我正在尝试使用.Net的Ajax.BeginForm来提交表单并获取对象列表.

@using (Ajax.BeginForm("ValidateEmployee", new AjaxOptions { OnBegin = "onBegin", OnSuccess = "onSucess", UpdateTargetId = "results"} )
Run Code Online (Sandbox Code Playgroud)

问题是,当我的控制器返回一个JsonResult并将我返回的列表转换为json时,永远不会调用OnSuccess回调,并且不会更新我的id为"results"的div.但是调用onBegin回调.控制器看起来像这样.

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);
}
Run Code Online (Sandbox Code Playgroud)

我已经确认Json(roles)将列表正确转换为有效的json.但我无法使用它,因为onSuccess永远不会运行.

奇怪的是,如果我不列表转换成JSON,就回到它作为.NET名单,这两个回调是碰我的元素,更新输出System.Collections.Generic.List'1 [Models.Role.所以它不是json,我没有办法使用数据.

那么为什么当我从控制器返回一个json对象时没有调用onSuccess?

我正在使用MVC 3,我正在引用jquery.unobtrusive-ajax.js.

谢谢你的帮助.

ysr*_*srb 8

我不认为您可以使用Ajax.BeginFormwith UpdateTargetId作为您的方案,因为您正在使用JsonResult该操作的结果.Ajax.BeginForm,给定UpdateTargetId将尝试将结果对象追加到您指定的元素.由于返回的是Json对象,因此会抛出错误.错误将是这样的:

    uncaught exception: [Exception... "Could not convert JavaScript argument arg 0 
[nsIDOMDocumentFragment.appendChild]" nsresult: "0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)"
 location: "JS frame :: http://localhost:58248/Scripts/jquery-1.4.4.js :: <TOP_LEVEL> :: 
line 5167" data: no]
Run Code Online (Sandbox Code Playgroud)

一旦UpdateTargetId删除,您应该看到onSuccess被触发.

function onSuccess(data){
 //data is the json object
 // do your html manipulation here
}
Run Code Online (Sandbox Code Playgroud)