根据用户角色过滤SelectList

时间:2017-11-16 20:14:54

标签: c# asp.net-mvc

将用户分配到某个项目时,我想将可用用户列表限制为具有“项目经理”角色的人员。我可以在语法上使用一些帮助,因为我似乎无法为Where方法获得LINQ语法。

创建动作(GET)

// This is the unfiltered version
ViewBag.AssignedToId = new SelectList(db.Users, "Id", "FullName");
// Attempt to filter   
ViewBag.AssignedToId= new SelectList(db.Users.Where(c => c.Roles.Contains("Project Manager")), "Id", "FullName");

创建视图

<div class="form-group">
     @Html.LabelFor(model => model.AssignedToId, "Choose a Project Manager", htmlAttributes: new { @class = "control-label col-md-2" })
         <div class="col-md-10">
             @Html.DropDownList("AssignedToId", null, htmlAttributes: new { @class = "form-control" })
             @Html.ValidationMessageFor(model => model.AssignedToId, "", new { @class = "text-danger" })
         </div>
</div>

我在DropDownList上收到错误

  

无法比较'System.Collections.Generic.ICollection'类型的元素。仅支持基本类型,枚举类型和实体类型。

3 个答案:

答案 0 :(得分:1)

假设这是您正在使用的实体框架,您会注意到db.Users的类型为DbSet,而db.Users.Where(...)的类型为IQueryable。我想你如果添加.ToList()就可以达到预期的效果,如下所示:

ViewBag.AssignedToId= new SelectList(db.Users.Where(c => c.Roles.Contains("Project Manager")).ToList(), "Id", "FullName");

答案 1 :(得分:0)

如果Roles是一个集合,那么我建议在LINQ to Entities查询之外创建"Project Manager"列表。此外,创建一个const string变量来保存"Project Manager"魔术字符串。如果该字符串永远改变,这将使您不必在每个使用它的位置更改该字符串。

public const string roleProjectManager = "Project Manager";

var lstProjectManagers = db.Users.Where(x => x.Roles.Contains(roleProjectManager)).ToList();

然后创建您的SelectList。

ViewBag.AssignedToId= new SelectList(lstProjectManagers, "Id", "FullName");

请告诉我这是否有帮助!

答案 2 :(得分:0)

我的问题的解决方案是将此代码包含在Controller Create Action(GET)中:

var role = db.Roles.SingleOrDefault(u => u.Name == "Project Manager");
var usersInRole = db.Users.Where(u => u.Roles.Any(r => (r.RoleId == role.Id)));
ViewBag.AssignedId = new SelectList(usersInRole, "Id", "FullName");

而不是:

ViewBag.AssignedToId = new SelectList(db.Users, "Id", "FullName");

然后将其包含在创建视图中:

<div class="form-group">
      @Html.LabelFor(model => model.AssignedToId, "Choose a Project Manager", htmlAttributes: new { @class = "control-label col-md-2" })
      <div class="col-md-10">
           @Html.DropDownListFor(Model => Model.AssignedToId, ViewBag.AssignedId as SelectList, null, htmlAttributes: new { @class = "form-control" })
           @Html.ValidationMessageFor(model => model.AssignedToId, "", new { @class = "text-danger" })
      </div>
</div>

替换此DropDownListFor:

@Html.DropDownList("AssignedToId", null, htmlAttributes: new { @class = "form-control" })