Ajax.BeginForm 返回未定义 JSON(开发工具显示 JSON 被返回)

Ajax.BeginForm returning undefined JSON (Dev Tools shows JSON being returned)

我在尝试从我的控制器 return 一个简单的 JSON 对象时遇到了一个奇怪的问题。在 firefox 调试工具中,我能够看到 JSON returned 就好了;但是,在我的 javascript 回调中,我在 console.log(data)

中得到了一个 undefined

Post(查看)

 @{
    string postAction = string.IsNullOrEmpty(Model._id) ? "AddCredential" : "EditCredential";
    string title = string.IsNullOrEmpty(Model._id) ? "Add" : "Edit";
    string onSuccessAction = "";

    if (!string.IsNullOrEmpty(Model.CallerLccation))
    {
        onSuccessAction = "Credentials.finishAddingCredFromEditPage();";
    }
    else
    {
        onSuccessAction = "General.init();$.fancybox.close();";
    }
}
<h3>@title Credential</h3>


@using (Ajax.BeginForm(postAction, new AjaxOptions { HttpMethod = "Post", OnSuccess = onSuccessAction, UpdateTargetId = "credentialList", InsertionMode = InsertionMode.Replace }))
{  

控制器(这里没有错误)

 public ActionResult AddCredential(CredentialViewModel viewModel)
    {

 //.......................      
                if (!string.IsNullOrEmpty(viewModel.CallerLccation))
            {
                //location the new credential being edited from is different than the normal location _CredentialList.cshtml

                return Json(new
                {
                    callerLocation = viewModel.CallerLccation,
                    credentialsDict = (object)JsonConvert.SerializeObject(GetCredentials(), Formatting.None),
                    newName = viewModel.Name,
                    newKey = newDoc["id"]

                });
            }




        return PartialView("_CredentialList", GetCredentialListViewModel());
    }  

回调

finishAddingCredFromEditPage: function (data) {
    //diff logic for diff places add credential is called from

    //UNDEFINED HERE
    console.log(data);
    switch(data.callerLocation) {
        case "edit":
            //reload phone dict
            allCredentials = data.credentialsDict;

            //add option to all dropdowns on the edit page
            $('.credentialDropdown').each(function(i) {
                $(this).prepend("<option selected></option>")
                    .attr("value", data.newKey)
                    .text(data.newName);
            });



            //reset stuff
            General.init();
            $.fancybox.close();
            break;
    }
},  

我试过的

  1. JsonRequestBehavior.AllowGet 添加到我的 return Json() 声明中
  2. 添加一个带有 id = credentialList 的虚拟 div 以查看它是否会被 JSON
  3. 填充
  4. 删除了 UpdateTargetIdInsertionMode 属性

我想也许在幕后 MVC 正在发送期望 HTML 的请求,因为存在 updateTargetId 但事实证明这不是问题所在。我检查了服务器的响应, JSON 确实存在。我不太确定要采取哪些其他步骤来解决此问题。

我明白了。显然,您不能在带有参数的回调上加上括号。不要在这方面引用我,因为我没有找到任何关于它的文档,但根据我的观察,情况确实如此。在我看来,我改变了

onSuccessAction = "Credentials.finishAddingCredFromEditPage();";  

onSuccessAction = "Credentials.finishAddingCredFromEditPage";  

终于能够在回调中得到一些东西