Step 0. 開啟Package Manager Console
輸入以下指令安裝MvcCheckBoxList
Install-Package MvcCheckBoxList |
1.分別建立User.cs & Role.cs
public class Role { public Role(int roleID, string name) { RoleID = roleID; Name = name; } public int RoleID { get; set; } public string Name { get; set; } } |
public class User {
public int? UserID { get; set; }
public string Account { get; set; }
public ICollection<Role> Roles = new List<Role>();
} |
2. 建立欲綁定在view上的model
public class UserViewModel {
public UserViewModel()
{
AvailableRoles = new List<Role>();
SelectedRoles = new List<Role>();
}
public int? UserID { get; set; }
public string Account { get; set; }
public IEnumerable<Role> AvailableRoles { get; set; }
public IEnumerable<Role> SelectedRoles { get; set; }
public PostedRoles PostedRoles { get; set; }
} public class PostedRoles {
public string[] RoleIDs { get; set; }
} |
注意PostedRoles 是用來接從view post回來的checkbox的選項
3. 建立Repository來取得Role的資料(為了簡化說明,所以沒有特意去串Db, 但這部分可以改寫成去Db裡撈Role的資料)
public static class RolesRepository {
private static List<Role> _roles;
public static void Initializer()
{
_roles = new List<Role>();
_roles.Add(new Role(1, "Admin"));
_roles.Add(new Role(2, "Guest"));
}
public static Role Get(int id)
{
return _roles.FirstOrDefault(X => X.RoleID == id);
}
public static IEnumerable<Role> GetAll()
{
if (_roles == null)
{
Initializer();
}
return _roles;
}
} |
4. 建立Service來處理增刪修査的商業邏輯
public class UserRoleService {
public Role GetRole(int id)
{
return RolesRepository.Get(id);
}
public IEnumerable<Role> GetAllRoles()
{
return RolesRepository.GetAll();
}
public void CreateNewUser(UserViewModel model)
{
User user = new User()
{
UserID = model.UserID,
Account = model.Account
};
foreach (var roleId in model.PostedRoles.RoleIDs)
{
Role role = RolesRepository.Get(roleId);
user.Roles.Add(role);
}
//Do something
}
} |
4. 在controller中新增Action, Create()來處理新增使用者的動作
並在其中建立一個 UserViewModel 然後以userRoleService.GetAll()附值給其成員AvailableRoles,最後再傳給viewpublic UserRoleService userRoleService = new UserRoleService(); public ActionResult Create() {
var usr = new UserViewModel();
usr.AvailableRoles = userRoleService.GetAll();
return View(usr);
} |
5. 使用 CheckBoxListFor實作CheckBox
<div class="form-group">
@Html.LabelFor(model => model.AvailableRoles, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.CheckBoxListFor( model => model.PostedRoles.RoleIDs,
model => model.AvailableRoles,
x => x.RoleID,
x => x.Name,
model => model.SelectedRoles)
</div>
</div> |
CheckBoxListFor會根據AvailableRoles 來建立CheckBox的內容
如果想設定default的選項
可以在步驟四的時候,附值給SelectedRoles
而PostedRoles.RoleIDs 則會儲存使用者最後submit的選擇
7. 處理從view回傳的資料
[HttpPost] public ActionResult Create(UserViewModel model) {
userRoleService.CreateNewUser(model);
return View();
} |
在這裡我們呼叫userRoleService.CreateNewUser 來處理建立新使用者的商業邏輯
結果:
Sample Code:
https://github.com/andy51002000/CheckBoxListForExample.git
留言
張貼留言