How to list users with role names in ASP.NET MVC 5

后端 未结 5 1124
栀梦
栀梦 2021-02-02 18:10

I have default project template of ASP.NET MVC 5 web site and I am trying to list all users with role names (not IDs).

The query is:

db.Users.Include(u =         


        
5条回答
  •  鱼传尺愫
    2021-02-02 18:30

    Thanks to @Callum Linington for his answer. Just Try to make it little bit clear for beginners like me. Here is steps to get a list of users with their roles.

    1- Create a view model called "UsersWithRoles" with some properties as shown below :

    2- Create a controller called "RolesController", and then add following piece of code in it.

            public ActionResult Index()
        {
            using (var context = new ApplicationDbContext())
            {
                var sql = @"
                SELECT AspNetUsers.UserName, AspNetRoles.Name As Role
                FROM AspNetUsers 
                LEFT JOIN AspNetUserRoles ON  AspNetUserRoles.UserId = AspNetUsers.Id 
                LEFT JOIN AspNetRoles ON AspNetRoles.Id = AspNetUserRoles.RoleId";
                //WHERE AspNetUsers.Id = @Id";
                //var idParam = new SqlParameter("Id", theUserId);
    
                var result = context.Database.SqlQuery(sql).ToList();
                return View(result);
            }
    
        }
    

    and here is what the RolesController should look like :

    3- Add Index page to Roles folder, and add the following code in it.

    @model IEnumerable
    

    Users

    @foreach (var user in Model) { }
    User Name Role
    @user.UserName @user.Role

    Here is the result

    Thanks.

提交回复
热议问题