我想创建一个CheckboxList,其中用户的角色被选中,并显示所有可用选项,UI是ok的。但是下面的代码不能工作
var applicationUser = db.AspNetUsers.Include(x => x.AspNetRoles)
.FirstOrDefault(x => x.Id == id.Value);
if (applicationUser == null)
{
return HttpNotFound();
}
var model = new ViewModels.UsuarioViewModel();
model.Id = applicationUser.Id;
model.UserName = applicationUser.UserName;
model.Name = applicationUser.Name;
model.Email = applicationUser.Email;
model.EmailConfirmed = applicationUser.EmailConfirmed;
model.PhoneNumber = applicationUser.PhoneNumber;
model.PhoneNumberConfirmed = applicationUser.PhoneNumberConfirmed;
model.Active = applicationUser.Active;
model.RolesList = db.AspNetRoles.Select(r => new SelectListItem
{
Selected =
applicationUser.AspNetRoles.Contains(x => x.Id == r.Id),
Text = r.Name,
Value = r.Name
}).ToList();
return View(model);
角色列表是一个IEnumerable SelectListItem
问题是"selected = applicationUser.AspNetRoles"。包含(x => x. id == r.Id)"部分。
编辑:好的,现在我有一个工作代码:
model.RolesList = db.AspNetRoles.ToList().Select(r => new SelectListItem
{
Selected = (applicationUser.AspNetRoles.
Where(x => x.Id == r.Id).ToList().Count > 0),
//Selected = false,
Text = r.Name,
Value = r.Name
});
我无法使用Contains使它工作。
我想知道在这个表达式中是否有使用contains的方法。
你不想要contains,你想要any
Selected = applicationUser.AspNetRoles.Any(x => x.Id == r.Id),
contains
查看给定元素是否在集合中,根本不是同一件事,我很惊讶您的代码甚至编译