My question is what is condition for the OnFailure callback to be called , 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...
Asked
Active
Viewed 2.9k times
4 Answers
18
<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>

Mangesh
- 3,987
- 2
- 31
- 52
-
2Thanks, that is useful, but I still want to know how does it know the call is failed... should I write something in the controller... – Rn2dy Aug 22 '11 at 21:32
-
Ya if the error is a business error eg Duplicate Name you need to send a error code which will be accepted on the OnSuccess().If the error is beyond your control it will be caught in OnError. – Mangesh Aug 22 '11 at 21:57
-
@MangeshPimpalkar if the error is "beyond your control" and you have customerrors turned on in web.config, OnFailure will never get called. – gangelo Feb 23 '12 at 03:11
-
I had a similar question. This link gives a detailed answer with an example. http://stackoverflow.com/a/37332246/4896260 – usr4896260 May 31 '16 at 18:49
4
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

Hernan Veiras
- 146
- 1
- 4
3
According to the official MSDN website: This function is called if the response status is not in the 200 range.

Piotr Lewandowski
- 365
- 3
- 10
0
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>

Mansoor Gee
- 1,071
- 8
- 20