You can use OnFailure
and OnSuccess
instead of OnComplete
; OnSuccess
gives you the data as a proper JSON object. You can find the callback method signatures burried in ~/Scripts/jquery.unobtrusive-ajax.min.js
which you should load on your page.
In your Ajax.BeginForm
:
new AjaxOptions
{
OnFailure = "onTestFailure",
OnSuccess = "onTestSuccess"
}
Script block:
<script>
//<![CDATA[
function onTestFailure(xhr, status, error) {
console.log("Ajax form submission", "onTestFailure");
console.log("xhr", xhr);
console.log("status", status);
console.log("error", error);
// TODO: make me pretty
alert(error);
}
function onTestSuccess(data, status, xhr) {
console.log("Ajax form submission", "onTestSuccess");
console.log("data", data);
console.log("status", status);
console.log("xhr", xhr);
// Here's where you use the JSON object
//doSomethingUseful(data);
}
//]]>
</script>
These signatures match success
and error
callbacks in $.ajax(…), which might not be such a surprise after all.
This was tested using asp.net-mvc-3 with jquery 1.6.3 and 1.7.2.