2011-04-15 87 views
1

正確的傢伙。我需要你的大腦,因爲我無法找到正確做到這一點的方法。MVC3使用CheckBox與複雜的viewmodel

我有一個視圖模型:

public class EditUserViewModel 
{ 
    public User User; 
    public IQueryable<ServiceLicense> ServiceLicenses; 
} 

用戶是不重要的,因爲我知道如何對付它。

ServiceLicenses具有以下實現:

public class ServiceLicense 
{ 
    public Guid ServiceId { get; set; } 
    public string ServiceName { get; set; } 
    public bool GotLic { get; set; } 
} 

獲取用戶的檢查清單是很酷。它像一個魅力。

<fieldset> 
    <legend>Licenses</legend> 
    @foreach (var service in Model.ServiceLicenses) 
    {  
    <p> 
     @Html.CheckBoxFor(x => service.GotLic) 
     @service.ServiceName 
    </p> 
    } 
</fieldset> 

我有越來越更新ServiceLicenses新籤服務對象回到我的控制器HttpPost的問題。爲了簡單起見,可以說它看起來像這樣:

[HttpPost] 
    public ActionResult EditUser(Guid id, FormCollection collection) 
    { 

     var userModel = new EditUserViewModel(id); 
     if (TryUpdateModel(userModel)) 
     { 
      //This is fine and I know what to do with this 
      var editUser = userModel.User; 

      //This does not update 
      var serviceLicenses = userModel.ServiceLicenses; 

      return RedirectToAction("Details", new { id = editUser.ClientId }); 
     } 
     else 
     { 
      return View(userModel); 
     } 
    } 

我知道我使用CheckBox的方式不對。我需要更改以使serviceLicenses在表單中選中的框更新?

回答

2

我明白,ServiceLicenses屬性是一個集合,你希望MVC活頁夾綁定到你的動作參數屬性。對,你應該在你的觀點與輸入連接索引e.g

<input type="checkbox" name = "ServiceLicenses[0].GotLic" value="true"/> 
<input type="checkbox" name = "ServiceLicenses[1].GotLic" value="true"/> 
<input type="checkbox" name = "ServiceLicenses[2].GotLic" value="true"/> 

前綴可能不是強制性的,但結合action方法參數的集合屬性時,它是非常方便的。爲此,我建議使用循環代替的foreach和使用Html.CheckBox幫手,而不是Html.CheckBoxFor

<fieldset> 
    <legend>Licenses</legend> 
    @for (int i=0;i<Model.ServiceLicenses.Count;i++) 
    {  
    <p> 
     @Html.CheckBox("ServiceLicenses["+i+"].GotLic",ServiceLicenses[i].GotLic) 
     @Html.CheckBox("ServiceLicenses["+i+"].ServiceName",ServiceLicenses[i].ServiceName)//you would want to bind name of service in case model is invalid you can pass on same model to view 
     @service.ServiceName 
    </p> 
    } 
</fieldset> 

不使用強類型的幫手就是在這裏個人喜好。如果你不希望索引你的投入是這樣,你也可以看看由史蒂夫這個偉大post senderson

編輯:我有blogged有關創建在asp.net MVC3主從表單這是在案件的相關列表綁定也是如此。

+0

我用史蒂夫森德森的方法去了。我認爲爲這類事情製作一組通用的HTML幫助程序會很有用。如果時間允許,我會查看它。謝謝您的幫助。 – TheGwa 2011-04-20 07:31:22

+0

@TheGwa肯定會很棒 – 2011-04-20 10:20:37