Ajax.BeginForm返回未定义的JSON(Dev Tools显示返回的JSON)

时间:2015-01-30 18:59:41

标签: jquery ajax json asp.net-mvc

我尝试从控制器返回一个简单的JSON对象时遇到了一个奇怪的问题。在firefox调试工具中,我能够看到JSON返回正常;但是,在我的javascript回拨中,我在undefined

中收到console.log(data)

帖子(查看)

 @{
    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. 删除了UpdateTargetIdInsertionMode属性
  4. 我想也许在幕后MVC正在发送期望HTML的请求,因为有一个updateTargetId,但事实并非如此。我检查了服务器的响应,JSON确实存在。我不太确定采取其他措施来解决这个问题。

1 个答案:

答案 0 :(得分:3)

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

onSuccessAction = "Credentials.finishAddingCredFromEditPage();";  

onSuccessAction = "Credentials.finishAddingCredFromEditPage";  

并且最终能够在回调中得到回报