2013-10-12 25 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

相关问题