Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 249
Rn2dy Avatar asked Aug 22 '11 04:08

Rn2dy


3 Answers

 <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>
like image 94
Mangesh Pimpalkar Avatar answered Nov 18 '22 18:11

Mangesh Pimpalkar


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
like image 4
Hernan Veiras Avatar answered Nov 18 '22 16:11

Hernan Veiras


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

AjaxOptions.OnFailure Property

like image 3
Piotr Lewandowski Avatar answered Nov 18 '22 16:11

Piotr Lewandowski