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

后端 未结 5 1122
栀梦
栀梦 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:34

    This is how I do it with MVC 5, Identity 2.0 and a custom user and role describe by John Atten

    In controller

    public virtual ActionResult ListUser()
        {            
            var users = UserManager.Users;
            var roles = new List();
            foreach (var user in users)
            {
                string str = "";
                foreach (var role in UserManager.GetRoles(user.Id))
                {
                    str = (str == "") ? role.ToString() : str + " - " + role.ToString();
                }
                roles.Add(str);
            }
            var model = new ListUserViewModel() {
                users = users.ToList(),
                roles = roles.ToList()
            };
            return View(model);
        }
    

    In ViewModel

    public class ListUserViewModel
    {
        public IList users { get; set; }
        public IList roles { get; set; }
    }
    

    And in my View

    @{
        int i = 0;
    }
    @foreach (var item in Model.users)
    {   
        @Html.DisplayFor(modelItem =>  item.Name)
        [... Use all the properties and formating you want ... and ] 
        @Model.roles[i]
        i++;
    }
    

提交回复
热议问题