模型验证的数据注释在mvc4中无法正常工作

时间:2016-11-22 20:48:36

标签: validation asp.net-mvc-4

我正在使用[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);
}

输出:

enter image description here

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

如果我在模型中使用RequiredIf注释,我得到了我想要的输出。

型号:

[DisplayName("Flat Fee Amount")]
[RequiredIf("DeliveryFee", "FlatFee", ErrorMessage = "Please enter flat fee amount.")]
public string FlatFeeAmount { get; set; }