6

当 ModelState 在控制器中无效时,我想调用“OnFailure”。

在我的登录视图中

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

 } 

在控制器中

[httpPost]
public ViewResult Login(LoginModel model)
{
   if (ModelState.IsValid)
   {

   }
   else
   { 
     ModelState.AddModelError("login is fail")
   }
   return View("Login",model)
}

所以我想在 ModelState 有效时调用 onSuccess 方法,如果它失败则只调用 OnError 方法并显示模型状态中的所有错误。

4

2 回答 2

19

这是你可以做的:

[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)
}

然后你只需要 Success 函数:

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

} 

您可以在其中测试在哪种情况下您是:

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);
    }
}

顺便说一句,如果您在刷新表单时使用不显眼的客户端验证,则需要手动强制解析新的验证规则,否则下次尝试提交表单时,客户端验证将不会工作:

} 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');
}
于 2012-09-26T10:24:47.827 回答
6

当您在 ModelState 中检测到问题时,将响应对象的 StatusCode 设置为 400 之类的值(您可以从 System.Net.HttpStatusCode 类中获取代码)

这将触发 onfailure 方法。

于 2012-09-26T12:14:15.643 回答