从角色admin中的用户获取下拉列表时出现问题

时间:2018-12-21 16:18:07

标签: c# asp.net model-view-controller drop-down-menu roles

您能帮我从Html.DropdownList列表中创建ViewBag吗? 当我使用以下代码时,出现错误,无法将列表转换为IEnumerable<SelectListItem>

var allUsers = db.Users.ToList();
var adminUsers = allUsers.Where(u => u.Roles.Select(r =>r.RoleId).Contains("1bafec08-fc36-41f6-a3f1-cc9a297e7481")).ToList();

ViewBag.Role = adminUsers;

这种显示方式无效:

@Html.DropDownList("PersonAssigned",(IEnumerable<SelectListItem>)ViewBag.Role, "Wybierz pracownika:", new { @class = "form-control" })

这还不是:

@Html.DropDownList("PersonAssigned", ViewBag.Role as SelectList, new { @class = "form-control" })

2 个答案:

答案 0 :(得分:0)

您需要先创建一个SelectList,然后再将其放入ViewBag中,

ViewBag.Role = new SelectList(adminUsers,"RoleId","RoleName");

,并在您的DropDownList助手视图中使用:

ViewBag.Role as SelectList

假设RoleName是表中的列名,否则您需要在表中输入角色文本。

答案 1 :(得分:0)

缺少与所需类型的映射,请考虑优化您的数据库查询

var roleId = Guid.Parse("1bafec08-fc36-41f6-a3f1-cc9a297e7481");
var adminUsers = db.Users.Where(x => x.Roles.Any(y => y.RoleId == roleId))
    .ToList()
    .Select(x => new SelectListItem() 
    {
        Text = x.RoleName,
        Value = x.RoleId
    })
    .ToList();

这将使此代码正常工作

@Html.DropDownList("PersonAssigned",(IEnumerable<SelectListItem>)ViewBag.Role, "Wybierz pracownika:", new { @class = "form-control" })