ASP.NET MVC3 AJAX.BeginForm AjaxOptions OnSuccess OnFailure Problem
My question is what is condition for the OnFailure callback to be called 开发者_StackOverflow, how does the runtime know the ajax call is failed (the ajax helper use some http response status code to indicate that? what it would be then?). And if the html of UpdateTargetId is updated no matter the ajax call is failed or success, then how should I handle the error properly then. Very confused...
<script type="text/javascript">
function OnSuccess() {
alert('Success');
}
function OnFailure(ajaxContext) {
var response = ajaxContext.get_response();
var statusCode = response.get_statusCode();
alert('Failure');
Here you can do whatever you want with the div.
$('#targetDiv').empty();
}
</script>
<div id="targetDiv">
@using (Ajax.BeginForm("Index", "Home",
new AjaxOptions
{
UpdateTargetId = "targetDiv",
OnSuccess ="OnSuccess",
OnFailure ="OnFailure"
})
{
...
}
</div>
It seems that in ASP.NET MVC 4 things had changed a little. I had to use the following properties to read the response and status:
ajaxContext.responseJSON
ajaxContext.responseText
ajaxContext.status
ajaxContext.statusText
According to the official MSDN website: This function is called if the response status is not in the 200 range.
AjaxOptions.OnFailure Property
OnFailure in AjaxOptions looks for a JavaScript function
<script>
function onError(ajaxContext) {
var response = ajaxContext.get_response();
var statusCode = response.get_statusCode();
alert("Error occured. Status code = " + statusCode);
}
</script>
In HTML write this to get alert when error comes.
<div id="updateDiv">
@using (Ajax.BeginForm(new AjaxOptions { HttpMethod = "Post", InsertionMode = InsertionMode.Replace, UpdateTargetId = "updateDiv", OnFailure = "onError" }))
{
@*Your HTML form code goes here.*@
}
</div>
精彩评论