2013-10-12 63 views
1

我想將數據庫中的所有角色顯示到下拉列表中。我以這種方式覆蓋了角色提供者的GetAllUser方法。將數據庫中的所有角色顯示到下拉列表中

 public string[] GetAllRoles() 
     { 
     string[] roles = Session.Query<RoleManager>() 
         .Select(r => r.roleName) 
         .ToArray(); 
     return roles; 
     } 

我在Controller中調用了這個方法。

[HttpGet] 
    public ActionResult DisplayAllRoles() 
    { 
     string[] allRoles = ((CustomRoleProvider)Roles.Provider).GetAllRoles(); 
     if (allRoles != null) 
     { 
      //bind dropDownlist list in view with all roles ??? 

      ModelState.AddModelError("", "List of All roles"); 

     } 
     else ModelState.AddModelError("","No role exists."); 
     return View(); 
    } 

查看:

 @Html.DropDownListFor(m => m.AllRoles,new SelectList (Model.AllRoles)) 

現在我的問題是,如何從roles.Can的那個字符串數組填充一個下拉列表請你寫我的情況的示例代碼。

回答

1

您可以使用SelectListItems。只要你所有的角色填充到視圖模型

public class RoleViewModel 
{ 
    public IEnumerable<SelectListItem> RolesList { get; set; } 
} 

public ActionResult DisplayAllRoles() 
{ 
     var roleModel = new RoleViewModel(); 

     //string[] allRoles = ((CustomRoleProvider)Roles.Provider).GetAllRoles(); 
     var allRoles = new[] { "role1", "role2" }; //hard coded roles for to demo the above method. 

     if (allRoles != null) 
     { 
      //bind dropDownlist list in view with all roles ??? 
      roleModel.RolesList = allRoles.Select(x => new SelectListItem() {Text = x, Value = x}); 
     } 
     else 
      ModelState.AddModelError("", "No role exists."); 

     return View(roleModel); 
} 

在你看來

@Html.DropDownListFor(m => m.RolesList, 
        new SelectList(
         Model.RolesList, 
         "Text", 
         "Value")) 

更新試玩選擇的值:

在RoleViewModel添加額外的屬性來獲取選定值

public class RoleViewModel 
    { 
    public RoleViewModel() 
    {} 

    public string SelectedRole { get; set; } 

    public IEnumerable<SelectListItem> RolesList { get; set; } 
    } 

在您的Razor視圖中,使用Html.BeginForm包裝下拉列表幷包含Submit按鈕。 還要更改下拉菜單以獲得Model.SelectedRole。

@using (Html.BeginForm("DisplayAllRoles", "Home")) 
{ 
    @Html.DropDownListFor(m => m.RolesList, 
     new SelectList(
     Model.RolesList, 
     "Text", 
     "Value", Model.SelectedRole)) 


    <p><input type="submit" value="Save" /></p> 
} 

在你的控制器,創建一個POST操作

[HttpPost] 
    public ActionResult DisplayAllRoles(FormCollection form) { 
     var selectedValue = form["RolesList"]; 
     return View(); 
    } 

以上了selectedValue是您選擇的一個。

+0

我不想硬編碼角色值。在我的情況下,字符串數組allroles包含我想填充下拉列表的角色。 – Wasfa

+0

當然。在你的例子中,硬編碼值將被真正的實現字符串[] allRoles =((CustomRoleProvider)Roles.Provider)替換.GetAllRoles();這就是爲什麼我評論這一行。 – Spock

+0

var scopeModel的範圍在if語句內,但我們正在外面迴應if.How可以在外部訪問if。 – Wasfa

相關問題