asp.net-mvc – 当ModelState为InValid时调用的Ajax.BeginForm OnFailur
发布时间:2020-05-24 16:09:58 所属栏目:asp.Net 来源:互联网
导读:当ModelState在控制器中无效时,我想调用“OnFailure”. 在我的LoginView中 @using (Ajax.BeginForm(Login, new AjaxOptions { HttpMethod = POST, UpdateTargetId = Login,InsertionMode = InsertionMode.Replace, OnSuccess = S
|
当ModelState在控制器中无效时,我想调用“OnFailure”. 在我的LoginView中 @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)
}
所以我想调用onSuccess方法,如果ModelState有效,如果失败,那么只调用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",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 – HttpUtility.HtmlEncode逃避太多了?
- asp.net-mvc – 全局访问Ninject内核
- asp.net-mvc – 如何让Visual Studio 2012检测虚拟目录是否
- asp.net-web-api – 如何从Web API获取IObservable
- asp.net – ASP计数器 – 不同计数器“桶”中类似命名的计数
- asp.net – 在自动生成的GridView列中防止HTML编码
- asp.net – 如何在web.config的MailSetting部分设置友好的电
- asp.net-mvc – 部署后不显示捆绑的css … ASP.NET MVC4
- 大文件上传到asp.net MVC
- ASP.NET错误处理
推荐文章
站长推荐
热点阅读
