2012-09-27 101 views
0

定模式:ASP.NET MVC3模型列表驗證

public class RegisterModel 
    { 
     <!-- some properties --> 

     [Required] 
     public Dictionary<DayOfWeek, bool> DaysAtWork { get; set; } 

     public RegisterModel() 
     { 
      DaysAtWork = new Dictionary<DayOfWeek, bool> 
         { 
          {DayOfWeek.Monday, true}, 
          {DayOfWeek.Tuesday, true}, 
          {DayOfWeek.Wednesday, true}, 
          {DayOfWeek.Thursday, true}, 
          {DayOfWeek.Friday, true} 
         }; 
     } 
    } 

控制器:

public ActionResult Register() 
    { 
     var model = new RegisterModel(); 

     return View(model); 
    } 

    [HttpPost] 
    public ActionResult Register(RegisterModel model) 
    { 
    <!-- and at these point in model state property for DaysAtWork 
    Dictionary is null and the whole model is invalid - and property in model 
    parameter is also null --> 
     if (ModelState.IsValid) 
     { 
      <!-- some logic here -->  
     }  
     return View(model); 
    } 

,並查看:

<!-- some code --> 
    @using (Html.BeginForm()) { 
    @Html.ValidationSummary(true, "Account creation was unsuccessful. Please correct the errors and try again.") 
    <div> 
     <fieldset> 
      <legend>Account Information</legend> 

      <div>Days at work</div> 

      <div> 
       Monday @Html.CheckBoxFor(m => m.DaysAtWork[DayOfWeek.Monday]) 
      </div> 
      <div> 
       Tuesday @Html.CheckBoxFor(m => m.DaysAtWork[DayOfWeek.Tuesday]) 
      </div> 
      <div> 
       Wednesday @Html.CheckBoxFor(m => m.DaysAtWork[DayOfWeek.Wednesday]) 
      </div> 
      <div> 
       Thursday @Html.CheckBoxFor(m => m.DaysAtWork[DayOfWeek.Thursday]) 
      </div> 
      <div> 
       Friday @Html.CheckBoxFor(m => m.DaysAtWork[DayOfWeek.Friday]) 
      </div> 


      <p> 
       <input type="submit" value="Register" /> 
      </p> 
     </fieldset> 
    </div> 
    } 

我有一個問題,而試圖註冊用戶,因爲在模型中,DaysAtWork屬性設置爲null。我該如何告訴asp使用在Register()HttpGet方法中創建的模型? 我做錯了什麼?

+0

Nevaran初始化構造函數中的Dictionary意味着在Model Constructor中爲字典分配一個內存。 – Shivkumar

回答

0

如果你犯了一個叫「周」型號或類似這樣:

public Week(){ 
public int Id; 
public int AccountId; 
public bool Monday; 
public bool ...; 
public bool Friday; 
} 

,並在您Registermodel添加到這個參考。

希望這會有所幫助!

+0

是的,它有幫助。謝謝! – Nevararn