Ajax.BeginForm, Calls Action, Returns JSON, How do I access JSON object in my OnSuccess JS Function?

前端 未结 4 1652
孤街浪徒
孤街浪徒 2020-12-24 03:23

Ajax.BeginForm calls an action and then returns JSON. How do I access JSON object in my OnComplete js function?

so my Ajax.BeginForm<

相关标签:
4条回答
  • 2020-12-24 03:29

    in asp.net mvc 4

    function CouponSubmitted(data) {
        alert(data.success); 
    }
    

    will return parsed 'json'

    0 讨论(0)
  • 2020-12-24 03:32

    I bumped into this question looking for the answer to do the same thing in ASP.NET MVC 4, and none of the above worked, so for anyone looking for the answer, the data is already encoded from json when you recive it in your js function

     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);
        }
    }
    

    This doesn't work with OnComplete I assuame it doesn't have paramtars to recive data.

    0 讨论(0)
  • 2020-12-24 03:44
    function OnSuccess(e) { //function CouponSubmitted(data) in the question
       var json = e.get_response().get_object();
       alert(json.success);
    }
    

    This is what the AJAX.BeginForm OnSuccess callback expects you to do to get your JSON back.

    Hope I saved someone else some time on this ridiculously under documented "feature?".

    0 讨论(0)
  • 2020-12-24 03:44

    this is an example of doing the post yourself but the concept is the same. Notice the parameter to the onsuccess function. the parameter gives you access to whaever the controller returned. If it is Json data then that is what you get. If the controler returned a partial view then you get the html for the view. You can call the JQuery $.ParseJSON() function on the returned data.

    $.post('/Assessment/GetAssessmentResults/' + SelectedId,   
    function onsuccess(e) {  
       var json_object = $.parseJSON(e);  
    }, "POST");  
    
    0 讨论(0)
提交回复
热议问题