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 =
I think its bad technique to execute dynamic SQL from your C# application. Below is my method:
Model:
public class ApplicationRole : IdentityRole
{
public ApplicationRole() : base() { }
public ApplicationRole(string name) : base(name) { }
public string Description { get; set; }
}
Controller:
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNet.Identity.EntityFramework;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Collections.Generic;
//Example for Details.
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var role = await RoleManager.FindByIdAsync(id);
// Get the list of Users in this Role
var users = new List();
// Get the list of Users in this Role
foreach (var user in UserManager.Users.ToList())
{
if (await UserManager.IsInRoleAsync(user.Id, role.Name))
{
users.Add(user);
}
}
ViewBag.Users = users;
ViewBag.UserCount = users.Count();
return View(role);
View (using ApplicationRole)
Roles.
-
@Html.DisplayNameFor(model => model.Name)
-
@Html.DisplayFor(model => model.Name)
-
@Html.DisplayNameFor(model => model.Description)
-
@Html.DisplayFor(model => model.Description)
List of users in this role
@if (ViewBag.UserCount == 0)
{
No users found in this role.
}
@foreach (var item in ViewBag.Users)
{
@item.UserName
}