我现在挣扎 .net Core 2 太久了,无法做一件非常简单的事情:创建一个具有多个角色的用户列表。
我有一个基于已发布示例的直接启动,ApplicationUser和ApplicationRole(IdentitySampleApplication;感谢创建者(。原始代码创建一个包含所有角色的选择列表。我想创建一个带有用户角色(分配给用户的角色(的选择列表。下面是原始代码。
public class UserController : Controller
{
private readonly UserManager<ApplicationUser> userManager;
private readonly RoleManager<ApplicationRole> roleManager;
public UserController(UserManager<ApplicationUser> userManager, RoleManager<ApplicationRole> roleManager)
{
this.userManager = userManager;
this.roleManager = roleManager;
}
[HttpGet]
public async Task<IActionResult> EditUser(string id)
{
EditUserViewModel model = new EditUserViewModel();
model.ApplicationRoles = roleManager.Roles.Select(r => new SelectListItem
{
Text = r.Name,
Value = r.Id
}).ToList();
if (!String.IsNullOrEmpty(id))
{
ApplicationUser user = await userManager.FindByIdAsync(id);
if (user != null)
{
model.Name = user.Name;
model.Email = user.Email;
model.ApplicationRoleId = roleManager.Roles.Single(r => r.Name == userManager.GetRolesAsync(user).Result.Single()).Id;
}
}
return PartialView("_EditUser", model);
我想将代码更改为以下内容:
public async Task<IActionResult> EditUser(string id)
{
EditUserViewModel model = new EditUserViewModel();
if (!String.IsNullOrEmpty(id))
{
ApplicationUser user = await userManager.FindByIdAsync(id);
if (user != null)
{
model.Name = user.Name;
model.Email = user.Email;
model.ApplicationRoles = userManager.GetRolesAsync(user);
}
}
EditUserViewModel 是
public class EditUserViewModel
{
public string Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public List<SelectListItem> ApplicationRoles { get; set; }
[Display(Name = "Role")]
public string ApplicationRoleId { get; set; }
}
我收到类型转换错误(cannot implicitly convert System.Threading.....IList<string> to System.Collections.....Rendering.SelectListItem
(,我无法解决。我显然没有走在正确的轨道上,但想不出其他解决方案。
我将非常感谢有人提供实用的解决方案。
由于已将List<string>
分配给List<SelectListItem>
属性,因此必须在 LINQ 中使用 Select 方法从List<string>
创建新List<SelectListItem>
,例如:userManager.GetRolesAsync(user(。Select(u=> new SelectListItem(( {Text=u}(;
感谢用户3688584,我已经创建了解决方案!下面的代码创建一个仅包含分配的角色的选择列表
[HttpGet]
public async Task<IActionResult> UsList(string id)
{
EditUserViewModel model = new EditUserViewModel();
if (!String.IsNullOrEmpty(id))
{
ApplicationUser user = await userManager.FindByIdAsync(id);
if (user != null)
{
var usr = await userManager.GetRolesAsync(user);
model.Name = user.Name;
model.Email = user.Email;
model.ApplicationRoles = usr.Select(u => new SelectListItem() {Text = u}).ToList();
}
}
return View("_UsList", model);
}
在上一个答案中添加.ToList()
就可以解决问题。