如何使用带有JSON结果的Ajax.BeginForm MVC助手? JSON结果中的参考数据

时间:2012-02-19 20:01:17

标签: asp.net-mvc-3 jquery

在帖子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对象“data”中的元素? 我的控制台日志显示以下内容: 日志:数据{“成功”:真实,“uri”:“/ Image / Confirm2?category = foo”}

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

console.log(“uri”,data.uri);

但结果如下:

日志:datauriundefined

1 个答案:

答案 0 :(得分: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
} 

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


事实证明问题出在您的控制器操作中,您在其中指定了错误的内容类型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 });