Rn2dy
Rn2dy

Reputation: 4190

ASP.NET MVC3 AJAX.BeginForm AjaxOptions OnSuccess OnFailure Problem

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...

Upvotes: 13

Views: 29195

Answers (4)

Hernan Veiras
Hernan Veiras

Reputation: 166

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

Upvotes: 4

Piotr Lewandowski
Piotr Lewandowski

Reputation: 385

According to the official MSDN website: This function is called if the response status is not in the 200 range.

AjaxOptions.OnFailure Property

Upvotes: 3

Mangesh
Mangesh

Reputation: 3997

 <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>

Upvotes: 18

Mansoor Gee
Mansoor Gee

Reputation: 1069

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>

Upvotes: 0

Related Questions