List User and Role in asp.net identity 2.0

会有一股神秘感。 提交于 2019-12-06 15:28:22

问题


How do i display a list of Users and their Roles in ASP.NET Identity 2.0.

Example...

John Doe - Admin Bob Smith - User

So far I have created a UserRoleViewModel

public string fname { get; set; }
public string rname { get; set; }

In the controller, I have done the following...

ApplicationDbContext db = new ApplicationDbContext();

UserRoleViewModel obj = new UserRoleViewModel();

var result = from u in db.Users
             select new UserRoleViewModel
             {
                fname = u.FirstName,
                rname = ???
             };

return View(result);

Is this the correct approach ? If yes, how do i get the role for the user in rname ?


回答1:


Does @Model.Roles in View strongly typed against @model WebApplicationName.Models.ApplicationUser does not work for you?

Controller:

public ActionResult NameOfTheView(){return View(db.Users.ToList());}



回答2:


Finally got a solution for my problem...

This is the ViewModel I created...

public class UserRoleViewModel
{
    public string fname { get; set; }
    public string rname { get; set; }
}

This is the Controller...

public ActionResult Users()
{
   var result = from user in db.Users
                from role in db.Roles
                where role.Users.Any(r => r.UserId == user.Id)
                select new UserRoleViewModel
                {
                    fname = user.FirstName,
                    rname = role.Name
                };

        return View(result);
}

And this is the view...

@model IEnumerable<ApplicationName.Models.UserRoleViewModel>
<ul>
    @foreach(var u in Model)
    { 
       <li>@u.fname - @u.rname</li>
    }
</ul>

I'm still new to LINQ, Lambda and MVC in general. If someone has a way to better this code, please feel free to add in your views.



来源:https://stackoverflow.com/questions/25945815/list-user-and-role-in-asp-net-identity-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!