Ajax.BeginForm OnFailure invoked when ModelState is InValid

17,141

Solution 1

Here's what you could do:

[HttpPost]
public ActionResult Login(LoginModel model)
{
    if (ModelState.IsValid)
    {
        // everything went fine and we want to redirect in this case =>
        // we pass the url we want to redirect to as a JSON object:
        return Json(new { redirectTo = Url.Action("SomeController", "SomeAction") });
    }
    else
    { 
        // there was an error => add an error message
        ModelState.AddModelError("login is fail")
    }

    // return a partial view instead of a full vire
    return PartialView("Login",model)
}

and then all you need is the Success function:

@using (Ajax.BeginForm("Login", new AjaxOptions { HttpMethod = "POST", OnSuccess = "loginAjaxSuccess" }))
{

} 

in which you could test in which case you are:

function loginAjaxSuccess(result) {
    if (result.redirectTo) {
        // the controller action returned a JSON result => it was a successful login
        // => we redirect the browser to this url
        window.location.href = result.redirectTo;
    } else {
        // the action returned a partial view with the form containing the errors
        // => we need to update the DOM:
        $('#Login').html(result);
    }
}

By the way if you are using unobtrusive client side validation in the case of error where you are refreshing the form you will need to manually force the parsing of the new validation rules, otherwise next time you attempt to submit the form, client validation won't work:

} else {
    // the action returned a partial view with the form containing the errors
    // => we need to update the DOM
    $('#Login').html(result);

    // Now that the DOM is updated let's refresh the unobtrusive validation rules on the form:
    $('form').removeData('validator');
    $('form').removeData('unobtrusiveValidation');
    $.validator.unobtrusive.parse('form');
}

Solution 2

When you detect the problem in the ModelState, set the StatusCode of the response object to something like 400 (You can get the code from the System.Net.HttpStatusCode class)

That will fire the onfailure method.

Si

Share:
17,141

Related videos on Youtube

Shivkumar
Author by

Shivkumar

Updated on September 15, 2022

Comments

  • Shivkumar
    Shivkumar about 1 year

    I want to call "OnFailure" when ModelState is not valid in controller.

    In My LoginView

     @using (Ajax.BeginForm("Login", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "Login",InsertionMode = InsertionMode.Replace, OnSuccess = "Success", OnFailure = "onError" }))
     {
    
     } 
    

    In Controller

    [httpPost]
    public ViewResult Login(LoginModel model)
    {
       if (ModelState.IsValid)
       {
    
       }
       else
       { 
         ModelState.AddModelError("login is fail")
       }
       return View("Login",model)
    }
    

    so i want call onSuccess Method if ModelState is valid and if it fail then call only OnError method with display all error which are in Model State.

  • Shivkumar
    Shivkumar about 11 years
    Drin when i use Viewresult it not allow me to use Json and also ViewResult can not return PartailView
  • Shivkumar
    Shivkumar about 11 years
    Thanks Darin it's really useful
  • Bacon
    Bacon almost 7 years
    This does not work on our test environment but works on my dev machine. On test, returning 400 doesn't fire the onfailure method. Any clues?