2016-11-22 52 views
-1

我正在使用[Required]進行字段驗證。情景是,有兩個複選框,並且基於一個選擇,用戶必須在textbox中添加值。如果它是空的,則顯示驗證錯誤。問題是,它第一次驗證它,但在之後的複選框選擇上顯示驗證消息。我在這裏錯過了什麼?模型驗證的數據註釋在mvc4中沒有按要求工作

型號:

[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

+0

你想要一個條件驗證屬性 - 例如,[萬無一失(http://foolproof.codeplex.com/)'[RequiredIf]'或同級(或寫自己) –

+0

你是對的。我會發布我的答案。 – CSharper

回答

0

我得到了我想要的輸出,如果我在模型中使用RequiredIf註釋。

型號:

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