不火

2015-06-28 24 views
0

一個需要驗證,我有以下型號:不火

public class Model1 
{ 
    [Required(ErrorMessage="E1")] 
    public string Name { get; set; } 
    [Required(ErrorMessage="E2")] 
    [RegularExpression(".+\\@.+\\..+")] 
    public string Email { get; set; } 
    [Required(ErrorMessage="E3")] 
    public bool WillAttend { get; set; } 
} 

控制器動作:

public ActionResult Model1() 
    { 
     Model1 m = new Model1(); 
     return View(m); 
    } 

和看法:

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken() 

    <div class="form-horizontal"> 
     <h4>Model1</h4> 
     <hr /> 
     @Html.ValidationSummary(true, "", new { @class = "text-danger" }) 
     <div class="form-group"> 
      @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" }) 
      <div class="col-md-10"> 
       @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } }) 
       @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" }) 
      </div> 
     </div> 

     <div class="form-group"> 
      @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" }) 
      <div class="col-md-10"> 
       @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } }) 
       @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" }) 
      </div> 
     </div> 

     <div class="form-group"> 
      @Html.LabelFor(model => model.WillAttend, htmlAttributes: new { @class = "control-label col-md-2" }) 
      <div class="col-md-10"> 
       <div class="checkbox"> 
        @Html.EditorFor(model => model.WillAttend) 
        @Html.ValidationMessageFor(model => model.WillAttend, "", new { @class = "text-danger" }) 
       </div> 
      </div> 
     </div> 

     <div class="form-group"> 
      <div class="col-md-offset-2 col-md-10"> 
       <input type="submit" value="Create" class="btn btn-default" /> 
      </div> 
     </div> 
    </div> 
} 

問題需要驗證的WillAttend財產不起作用。即使在操作方法中,ModelState.IsValid也是如此。爲什麼以及如何做WillAttend是必需的?

+1

您何時期望Required驗證器啓動? Bool只有兩個可能的值(True和False),並且都滿足WillAttend屬性具有值的要求。看看這個問題[對於MVC .net屬性上的必需屬性,True的布爾值](http://stackoverflow.com/questions/7930808/boolean-value-of-true-for-required-attribute-on-mvc -net屬性)。 –

回答

1

目前,您的必需屬性只是檢查是否指定了一個值。由於布爾值爲true或false,驗證將永遠不會失敗。

您可以標記布爾可爲空:

public bool? WillAttend { get; set; } 

,或者你可以嘗試做一個自定義的驗證,如果你試圖強迫他們以檢查框,如in this link