【发布时间】:2016-04-11 14:18:38
【问题描述】:
我正在使用数据注释进行客户端验证。我有两种使用[Required] 和[RequiredIfTrue] 的场景。问题是我的条件验证不起作用。
工作:
型号:
[DisplayName(@"Custom Email Confirmation Address")]
[EmailAddress(ErrorMessage = @"Invalid Email Address")]
public string CustomEmailConfirmationAddress { get; set; }
查看:
<div>
<%=Html.RequiredLabelFor(m => m.CustomEmailConfirmationAddress) %>
<%=Html.TextBoxFor(m => m.CustomEmailConfirmationAddress, new { maxlength = 100 })%>
<%=Html.ValidationMessageFor(m => m.CustomEmailConfirmationAddress)%>
</div>
不工作:
场景 = 如果选中 ShowConceptOptInMessage 而不是使 ConceptEmailOptInMessage 和 PrivacyPolicy 字段成为必需。
型号:
[DisplayName("Show Concept Opt-In Message")]
public bool ShowConceptOptInMessage { get; set; }
[RequiredIfTrue("ShowConceptOptInMessage", ErrorMessage = "Concept Email Opt-In Message is required")]
[DisplayName("Concept Email Opt-In Message")]
public string ConceptEmailOptInMessage { get; set; }
[RequiredIfTrue("ShowConceptOptInMessage", ErrorMessage = "Concept Privacy Policy is required")]
[DisplayName("Concept Privacy Policy")]
public string PrivacyPolicy { get; set; }
查看:
<div>
<%=Html.LabelFor(m => m.ShowConceptOptInMessage) %>
<%=Html.CheckBoxFor(m => m.ShowConceptOptInMessage)%>
<%=Html.ValidationMessageFor(m => m.ShowConceptOptInMessage)%>
</div>
<div>
<%=Html.LabelFor(m => m.ConceptEmailOptInMessage) %>
<%=Html.TextAreaFor(m => m.ConceptEmailOptInMessage, new { maxlength = 1000 })%>
<%= Html.ValidationMessageFor(m => m.ConceptEmailOptInMessage)%>
</div>
<div>
<%=Html.LabelFor(m => m.PrivacyPolicy) %>
<%=Html.TextAreaFor(m => m.PrivacyPolicy)%>
<%= Html.ValidationMessageFor(m => m.PrivacyPolicy)%>
</div>
两种场景的控制器方法:
控制器:
[HttpPost]
public ActionResult Edit(ConceptConfigurationModel model)
{
try
{
if (this.ModelState.IsValid)
{
// model
this.ConceptManager.SaveConcept(model);
model.Submitted = true;
}
}
catch (BusinessLogicException ex)
{
this.ModelState.AddModelError("ConceptName", ex.Message);
}
ModelState.Clear();
this.ConceptManager.FillConceptModel(model);
return View(model);
}
【问题讨论】:
-
不知道为什么你接受了一个与你的问题无关的答案,这只是一个可怕的黑客攻击。假设您使用 foolproof
[RequiredIfTrue]并且您已包含相关脚本,那么您的代码可以正常工作。
标签: c# asp.net-mvc-4 data-annotations