2011-11-02 79 views
7

我需要顯示覆選框列表,可以選中多個複選框。MVC3如何將多個複選框綁定到ViewModel中的1個屬性

當用戶點擊提交,這些複選框的值需要進入的視圖模型的屬性......這是我走到這一步......

public class RegisterModel 
{ 
    public List<string> Roles { get; set; } 
    public List<RoleModel> SelectedRoles { get; set; }  
} 
public class RoleModel 
{ 
    public string RoleName { get; set; } 
} 

在視圖我想要做到這一點...

@foreach (var role in Model.Roles) 
{ 
    @Html.CheckBoxFor(m => m.SelectedRoles, role.RoleName)@role.RoleName 
} 

我得到以下錯誤:

CS0029: Cannot implicitly convert type 'System.Collections.Generic.List<string>' to 'bool' 

誰能告訴我什麼,我做錯了什麼?

回答

17

簡單:調整您的視圖模型以符合您的視圖要求(即顯示某些角色的複選框列表),使用編輯器模板並避免在視圖中編寫循環。

所以:

視圖模型:

public class RegisterModel 
{ 
    public List<RoleModel> Roles { get; set; } 
} 

public class RoleModel 
{ 
    public string RoleName { get; set; } 
    public bool Selected { get; set; } 
} 

控制器:

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     var model = new RegisterModel 
     { 
      Roles = new[] 
      { 
       new RoleModel { RoleName = "administrator" }, 
       new RoleModel { RoleName = "developer" }, 
       new RoleModel { RoleName = "janitor :-)" }, 
      }.ToList() 
     }; 
     return View(model); 
    } 

    [HttpPost] 
    public ActionResult Index(RegisterModel model) 
    { 
     // at this stage the model will contain all the 
     // information you need 
     return View(model); 
    } 
} 

視圖(~/Views/Home/Index.cshtml):

@model RegisterModel 

@using (Html.BeginForm()) 
{ 
    @Html.EditorFor(x => x.Roles) 
    <button type="submit">OK</button> 
} 

編輯模板(~/Views/Home/EditorTemplates/RoleModel.cshtml ):

@model RoleModel 

<div> 
    @Html.HiddenFor(x => x.RoleName) 
    @Html.CheckBoxFor(x => x.Selected) 
    @Html.LabelFor(x => x.Selected, Model.RoleName) 
</div> 
+0

感謝您的快速響應! – thiag0

+0

@ thiag0,不客氣。 –

+0

這麼簡單,它的效果很棒! – tsquillario

相關問題