Ajax.BeginForm,Calls Action,返回JSON,如何访问OnSuccess JS函数中的JSON对象?

Jas*_*son 19 asp.net-mvc jquery json

Ajax.BeginForm调用一个动作,然后返回JSON.如何在OnCompletejs函数中访问JSON对象?

所以我的Ajax.BeginForm样子......

using (Ajax.BeginForm("Coupon", new AjaxOptions { OnSuccess = "CouponSubmitted" }))
Run Code Online (Sandbox Code Playgroud)

我的OnSuccess功能看起来像这样......

function CouponSubmitted() {
    var data = response.get_response().get_object();
    alert(data.success);
}
Run Code Online (Sandbox Code Playgroud)

我也试过......

function CouponSubmitted(data) {
    alert(data.success); 
}
Run Code Online (Sandbox Code Playgroud)

我的控制器"优惠券"返回此...

return Json(new { success = false, nameError = nameError, emailError = emailError });
Run Code Online (Sandbox Code Playgroud)

关于如何访问返回的Json的任何想法?

Jas*_*son 34

function OnSuccess(e) { //function CouponSubmitted(data) in the question
   var json = e.get_response().get_object();
   alert(json.success);
}
Run Code Online (Sandbox Code Playgroud)

这就是AJAX.BeginForm OnSuccess回调期望你做的事情,以恢复你的JSON.

希望我在其他时间节省了一些其他可笑的"功能"吗?

  • [`couponSubmitted(data,status,xhr)`](http://stackoverflow.com/a/7467032/907779)在[tag:asp.net-mvc3]中. (8认同)

for*_*atc 14

我碰到了这个问题,寻找在ASP.NET MVC 4中做同样事情的答案,并且上述方法都没有,所以对于任何寻找答案的人来说,当你在js中重用它时,数据已经从json编码了功能

 public ActionResult Something()
 {
    return Json(new { result = 0, message = "Testing" });
 } 

...

 new AjaxOptions { HttpMethod = "POST", OnSuccess= "something" }

...

function something(data) {
    switch(data.result)
    {
    case 1:
       alert(data.result)
    break;
    case 0:
        alert(data.result)
    break;
    case -1:
        alert(data.result)
    break;
    default:
        alert(data.message);
    }
}
Run Code Online (Sandbox Code Playgroud)

这不适用于OnComplete我认为它没有paramtars来重现数据.