asp.net-mvc - 当 ModelState 无效时调用 Ajax.BeginForm OnFailure

标签 asp.net-mvc asp.net-mvc-3 asp.net-ajax

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

在我的登录 View 中

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

 } 

在 Controller 中

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

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

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

最佳答案

您可以执行以下操作:

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

关于asp.net-mvc - 当 ModelState 无效时调用 Ajax.BeginForm OnFailure,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12599090/

相关文章:

asp.net - 如何动态创建UpdatePanel触发器

asp.net-mvc - 如何在 MVC4/Razor 中向访问者显示数据库名称?

asp.net-mvc-3 - 如何使用 EF-Code-First 将大型表分成多个离散类型

css - 在 CSS 文件中格式化 WebGrid

c# - 使用 ASP.Net MVC 3 将图像上传到 Amazon S3

asp.net - 关于什么以及如何不使用 ASP.NET AJAX 的资源?

c# - 我应该在哪里找到 MVC Razor 中的共享@helper 函数

asp.net-mvc - 如何在 Html.TextboxFor 上强制大写

css - 网站发布时提供的 MVC 应用程序模板圆 Angular 消失

asp.net-mvc - 使用 javascript 创建 Ajax.ActionLink