【问题标题】:MVC Ajax.BeginForm calling an action that returns JsonResult does not succeed on clientMVC Ajax.BeginForm 调用返回 JsonResult 的操作在客户端上未成功
【发布时间】:2011-07-31 11:09:48
【问题描述】:

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

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

问题是,当我的控制器返回一个 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);
}

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

奇怪的是,如果我不将列表转换为 json 并将其作为 .Net 列表返回,则两个回调都会被命中,并且我的元素更新输出 System.Collections.Generic.List'1[Models.Role]。所以它不是json,我没有办法使用数据。

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

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

感谢您的帮助。

【问题讨论】:

  • 我认为你漏掉了一点。 @using (Ajax.BeginForm("ValidateEmployee", new AjaxOptions { OnBegin = "onBegin", onSuccess = "onSucess", UpdateTargetId = "results"}
  • 而且应该是 OnSuccess (大写 O)
  • 糟糕。创建帖子时我的错字。编辑帖子以更正它。谢谢。

标签: asp.net-mvc-3 jsonresult ajax.beginform


【解决方案1】:

我认为您不能将Ajax.BeginFormUpdateTargetId 一起用于您的场景,因为您使用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]

删除UpdateTargetId 后,您应该会看到 onSuccess 被触发。

function onSuccess(data){
 //data is the json object
 // do your html manipulation here
}

【讨论】:

  • 你完全正确。删除 UpdateTargetId 修复了它。谢谢!我会投票赞成您的答案,但没有所需的声誉。 :(
猜你喜欢
  • 1970-01-01
  • 2012-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-08
  • 2014-07-27
  • 1970-01-01
相关资源
最近更新 更多