List of users and roles in asp.net identity 2.0

How to 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 did 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 right approach? If so, how do I get the user role in rname?

0
source share
2 answers

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 anyone has a way to improve this code, feel free to add your opinions.

0
source

@Model.Roles , @model WebApplicationName.Models.ApplicationUser?

:

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

Source: https://habr.com/ru/post/1618334/


All Articles