我是MVC5的新手,我正在尝试显示用户详细信息的列表视图以及他们所在角色的名称。我已经使用MVC身份设置了角色。
以下是我的ViewModel
public class UserRoleViewModel
{
public string UserRoleVMId { get; set; }
public string Title { get; set; }
public string FirstName { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
public string Role { get; set; }
public bool AccountEnabled { get; set; }
}
我的控制员:
public ActionResult Index()
{
var model = (from d in db.Users
select new UserRoleViewModel()
{
UserRoleVMId = d.Id,
Title = d.Title,
FirstName = d.FirstName,
Surname = d.Surname,
Email = d.Email,
AccountEnabled = d.AccountEnabled,
Role = d.Role.Name
}).ToList();
return View(model);
}
我不确定如何显示角色名称并收到错误消息
does not contain the definition for Role and no extension method Role
at
Role = d.Role.Name
非常感谢任何帮助
由于
答案 0 :(得分:1)
您可以使用GetRoles
方法:
viewModel.RolesForThisUser = UserManager.GetRoles(userId).ToList();
当您想要显示一个用户的详细信息时,这非常有用。
您应该使用属性Roles,因为用户可以拥有多个角色:
public ActionResult Index()
{
using(var context = new IdentityDbContext()){
viewModel =
context.Users
.Include("Roles")
.Select(u =>
new UserRoleViewModel {
UserRoleVMId = u.Id,
Title = u.Title,
FirstName = u.FirstName,
Surname = u.Surname,
Email = u.Email,
AccountEnabled = u.AccountEnabled,
Role = u.Roles.First().Role.ToString()
}
).ToList();
}
return View(viewModel);
}
答案 1 :(得分:0)
您可以使用此代码
return view(db.Users.ToList());
并在您最顶层的视图中使用
@model IEnumerable<YourProjectName.Models.Users>
并将此foreach用于显示内容
@foreach(var item in Model){<p>@item.Title</p> and etc }