views:

33

answers:

2

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

so my ajax.beginform looks like this...

using (Ajax.BeginForm("Coupon", new AjaxOptions { OnSuccess = "CouponSubmitted" }))

and my OnSuccess Function Looks like this...

function CouponSubmitted() {
            var data = response.get_response().get_object();
            alert(data.success);
           }

I also tried...

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

My controller "Coupon" returns this...

return Json(new { success = false, nameError = nameError, emailError = emailError });

Any ideas on how to access the Json that gets returned?

A: 

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");  
Kevin Koenig
Unfortunately that doesn't work in this instance.
Blankasaurus
A: 
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?".

Blankasaurus