2015-04-19 115 views
0

我已經在mvc5應用中使用種子創建了一些演示用戶和一些角色。成功將用戶分配給少數角色。一切正常。現在,我想,但我不知道如何建立用戶管理,UI界面,這將是負責mvc5中的用戶角色管理

  • 創建/編輯用戶,並分配給一個或多個角色

角色將被硬編碼( RoleOne,RoleTwo,RoleThree)。

我想創建視圖自定義視圖模型,將只需要幾個屬性

Username 
Password 
Email 

,並在視圖分配槽複選框的角色列表。

問題是:我應該如何在viewmodel上構造這個Roles屬性以及如何在後控制器動作端接收已檢查的角色?

+0

您可以在viewmodel中爲'selected'選擇一個布爾屬性,然後在所有的複選框中循環查看確實選中了哪些。 –

回答

2

您的問題歸結爲您要在viewmodel中發佈子項目集合的用例,其中子項代表UI中的複選框。

爲您的視圖創建一個視圖模型,您將在其中創建一個用戶並同時分配角色。

public class AddUserRoleVM 
{ 
    public string UserName { set; get; } 
    public List<UserRoleVM> Roles { set; get; } 
    public AddUserRoleVM() 
    { 
     Roles=new List<UserRoleVM>(); 
    } 
} 

public class UserRoleVM 
{ 
    public int RoleId { set; get; } 
    public String RoleName { set; get; } 
    public bool IsSelected { set; get; } 
} 

現在在你的GET操作,創建視圖模型AddUserRoleVM的objecct,初始化Roles集合屬性,並將其發送到視圖。

public ActionResult Roles() 
{ 
    var vm = new AddUserRoleVM(); 
    vm.Roles = GetRoles(); 
    return View(vm); 
} 

private List<UserRoleVM> GetRoles() 
{ 
    //Hard coded for demo.You should get the roles from db 
    return new List<UserRoleVM> 
    { 
     new UserRoleVM {RoleId = 1, RoleName = "Admin"}, 
     new UserRoleVM {RoleId = 2, RoleName = "Editor"} 
    }; 
} 

現在創建一個Views/YourControllerName下稱爲EditorTemplates文件夾。然後在下面的內容下創建一個名爲UserRoleVM.cshtml的新視圖。

@model ReplaceYourNamespaceHere.UserRoleVM 
<div> 
    @Html.HiddenFor(s=>s.RoleId) 
    <label>@Model.RoleName</label> 
    @Html.CheckBoxFor(s=>s.IsSelected) 
</div> 

enter image description here

現在我們的主要觀點(Roles.cshtml),使用Html.EditorFor HTML輔助方法來把這個觀點。

@model YourNameSpaceHere.AddUserRoleVM 
<h2>Create User</h2> 
@using (Html.BeginForm()) 
{ 
    <label>UserName : </label> @Html.TextBoxFor(s=>s.UserName) 
    <label>Roles:</label> 
    @Html.EditorFor(s=>s.Roles) 
    <input type="submit"/> 
} 

現在,當您發佈表單數據,請檢查您發佈模型的角色收集和驗證每個項目的IsSelected財產。

enter image description here

乾杯!