[英]Disable client side validation for some fields in ASP.NET MVC
如何有条件地禁用某些字段的客户端验证?
这是我需要做的例子:
它不起作用,因为:当用户单击第二个(确认屏幕)上的“重新发送”按钮时,客户端验证将无法通过。 它会说,即使没有字段,也需要电子邮件。 如何在确认页面发送给用户之前禁用JavaScript验证电子邮件?
示例ASP.NET MVC页面
<%if (Model.Confirm == false){ %>
<% using (Html.BeginForm()) { %>
Your email: <%: Html.EditorFor(m => m.Email) %>
Your name: <%: Html.EditorFor(m => m.Name) %>
<input type="submit" value="Send Email" />
<% } %>
<%} else{ %>
The e-mail was send! You can write your name and click button to resend it.
<% using (Html.BeginForm()) { %>
Your name: <%: Html.EditorFor(m => m.Name) %>
<input type="submit" value="Resend me email again" />
<% } %>
<% } %>
在模型中,“ Email
和“ Name
均为必填字段,以强制进行客户端验证。
控制器动作示例
public ActionResult Index(){
return new MyModel {Confirm = false;}
}
[HttpPost]
public ActionResult Index(MyModel model){
if(DataHelper.isKnown(model.Name)){
//send e-mail to the address corresponding to name in database
}
if(!ModelState.IsValid) {
return View(model);
}
//Send e-mail to address in email
//store pair name->email to database
model.Confirm = true;
return View(model);
}
只是一个简单的解决方案,我将隐藏电子邮件字段以进行第二次确认并保留其值。
<%} else{ %>
The e-mail was send! You can write your name and click button to resend it.
<% using (Html.BeginForm()) { %>
<%: Html.HiddenFor(m => m.Email) %>
Your name: <%: Html.EditorFor(m => m.Name) %>
<input type="submit" value="Resend me email again" />
<% } %>
<% } %>
我认为,这不是全部问题还是全部问题。 因此,您需要为该视图禁用客户端验证,并手动检查要验证的控件。 (在我的头顶)。
编辑:如果我想进行手动客户端验证,我将使用jQuery,因为它在此类任务中非常简单。
为什么不使用两种不同的视图? 您不必重定向。 我认为您在这里违反了SRP。 这种观点有多个目的。
public ActionResult SubmitEmail(Model model)
{
if(!emailWasSent)
return View("FirstView");
else
return View("ConfirmationView");
}
这样,第一个视图可以进行客户端验证,而第二个视图则不能选择接受它并按照自己的意愿进行操作。
将“禁用”属性添加到元素后,可以将其从客户端验证中排除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.