我正在使用[Required]
进行字段验证。场景是,有两个复选框,基于一个选择,用户必须在textbox
中添加值。如果它为空,则显示验证错误。问题是,它首次验证它,但在之后的复选框选择中显示验证消息。我在这里缺少什么?
型号:
[DisplayName("Flat Fee Amount")]
[Required(ErrorMessage = "Enter flat fee amount.")]
public string FlatFeeAmount { get; set; }
查看:
<div id="show-delivery-fee">
<div>
<%= Html.RadioButtonFor(m => m.DeliveryFee, "All", new {id = "All"}) %>
<%= Html.Label("All", new {@for = "All"}) %>
</div>
<div>
<%-- BASED ON THIS CHECKBOX SELECTION DISPLAY VALIDATION MESSAGE--%>
<%= Html.RadioButtonFor(m => m.DeliveryFee, "FlatFee", new {id = "FlatFee"}) %>
<%= Html.Label("Flat Fee", new {@for = "FlatFee"}) %>
</div>
<div>
<%= Html.LabelFor(m => m.FlatFeeAmount) %>
<%= Html.TextBoxFor(m => m.FlatFeeAmount, new {maxlength = "5"}) %>
<%= Html.ValidationMessageFor(m => m.FlatFeeAmount)%>
</div>
</div>
控制器:
[HttpPost]
[RequiredAccessRights(AllowRightsOr = new[] { SystemRight.EditDelivery })]
[AuditActionFilter("Save store delivery. Store id: {model.StoreId.Value}")]
public ActionResult Delivery(StoreDeliveryModel model)
{
if(this.ModelState.IsValid)
{
try
{
this.StoreManager.SaveDeliveryModel(model);
model.Submitted = true;
}
catch (ValidationException exc)
{
this.ModelState.AddModelError("", exc.Message);
}
}
return View(model);
}
输出:
答案 0 :(得分:0)
如果我在模型中使用RequiredIf
注释,我得到了我想要的输出。
型号:
[DisplayName("Flat Fee Amount")]
[RequiredIf("DeliveryFee", "FlatFee", ErrorMessage = "Please enter flat fee amount.")]
public string FlatFeeAmount { get; set; }