【问题标题】:How to use Ajax.BeginForm MVC helper with JSON result? Reference data in JSON Result如何将 Ajax.BeginForm MVC 助手与 JSON 结果一起使用? JSON 结果中的参考数据
【发布时间】:2012-03-10 07:08:20
【问题描述】:

How to use Ajax.BeginForm MVC helper with JSON result? Joel 的帖子中引用了如下解决方案:

function onTestSuccess(data, status, xhr) { 

    console.log("data", data); 
    console.log("xhr", xhr); 
    console.log("status", status); 

    // Here's where you use the JSON object 
    //doSomethingUseful(data); 
} 

如何在我的代码中引用 JSON 对象“数据”中的元素? 我的控制台日志显示以下内容: LOG: 数据{"success":true,"uri":"/Image/Confirm2?category=foo"}

我正在尝试在我的 jquery 代码中使用“uri”的值。我试过了:

console.log("uri", data.uri);

但结果如下:

日志:datauriundefined

【问题讨论】:

    标签: asp.net-mvc-3 jquery


    【解决方案1】:
    function onTestSuccess(data, status, xhr) { 
        var uri = data.uri;
        // uri = '/Image/Confirm2?category=foo' at this stage 
        // so you could do something useful with it
    } 
    

    此外,您需要在设置 Ajax.BeginForm 而不是 OnComplete="onTestSuccess" 时使用 AjaxOptions 中的 OnSuccess="onTestSuccess" 设置。


    事实证明,问题出在您的控制器操作中,您在其中指定了不正确的 Content-Type text/html

    所以而不是:

    String uri = Url.Action("Confirm2", "Image", new RouteValueDictionary(new { category = "foo" })); 
    return Json(new { success = true, uri = uri }, "text/html");
    

    你应该使用:

    String uri = Url.Action("Confirm2", "Image", new RouteValueDictionary(new { category = "foo" })); 
    return Json(new { success = true, uri = uri });
    

    【讨论】:

    • 不幸的是,我仍然没有取得太大的成功。
    • 见代码:var uri = data.uri;控制台.log(uri);显示 LOG: undefined
    • @user1219694,您应该在 AjaxOptions 中使用 OnSuccess="onTestSuccess" 而不是 OnComplete="onTestSuccess"
    • 是的——这就是我正在做的@using (Ajax.BeginForm("create", "Guide", new AjaxOptions { HttpMethod = "Post", OnSuccess = "JsonCreateGuide_OnComplete" }))跨度>
    • 你的控制器操作return Json(new { uri = "/Image/Confirm2?category=foo" })?你也可以试试console.log($.parseJSON(data).uri);
    猜你喜欢
    • 2010-09-23
    • 2014-01-11
    • 2010-11-13
    • 1970-01-01
    • 2015-05-18
    • 1970-01-01
    • 2011-06-21
    • 2011-09-16
    • 2017-03-03
    相关资源
    最近更新 更多