Reputation: 481
I want to show all users with a specified role name. What I am doing is just specify a role name in the View. If this name exists then show all the related users (this works now), or display nothing (Exceptions arose here). Here is my code in controller:
public ActionResult ViewUser(string roleName)
{
var UsersContext = new ApplicationDbContext();
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
if (roleManager.RoleExists(roleName))
{
var role = roleManager.FindByName(roleName).Users.First();
var usersInRole = UsersContext.Users.Where(u => u.Roles.Select(r => r.RoleId).Contains(role.RoleId)).ToList();
return View(usersInRole);
}
else
{
return View();
}
}
Here is the code with a non-existing role name called "Worker" in View:
@Html.ActionLink("Manage User", "ViewUser", "Home", new { @roleName="Worker"}, new { style = "color:white" })
The following screenshot is the result when I specify "Customer" which exists in database as the role name. If I specify another non-existing name, the result should have contained no user list.
Upvotes: 1
Views: 4583
Reputation: 24957
Assumed that you're returning User
entity instance from usersInRole
collection inside if
block, you can restructure if
block to automatically return empty List<User>
collection if no conditions are met (also added null
checking for FindByName()
method):
public ActionResult ViewUser(string roleName)
{
var UsersContext = new ApplicationDbContext();
var usersInRole = new List<User>(); // assign instance before if conditions
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
if (roleManager.RoleExists(roleName))
{
// change to FirstOrDefault is more recommended
var role = roleManager.FindByName(roleName).Users.FirstOrDefault();
if (role != null)
{
usersInRole = UsersContext.Users.Where(u => u.Roles.Select(r => r.RoleId).Contains(role.RoleId)).ToList();
}
}
return View(usersInRole);
}
Or simply returning empty list in else
block:
var emptyList = new List<User>();
return View(emptyList);
Additionally, make sure that you're using @model User
to bind it in view page.
Upvotes: 2
Reputation: 177
public ActionResult ViewUser(string roleName)
{
var UsersContext = new ApplicationDbContext();
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
if (roleManager.RoleExists(roleName))
{
var role = roleManager.FindByName(roleName).Users.First();
var usersInRole = UsersContext.Users.Where(u => u.Roles.Select(r => r.RoleId).Contains(role.RoleId)).ToList();
return View(usersInRole);
}
else
{
return View(new List<Users>());
}
}
Upvotes: 0
Reputation: 13
I hope i am getting you rite here ..... You want to return an empty list, that you can achieve with below :
private List<myClass> GetList(){
List<myClass> list = new List<myClass>();
list.Add(new myClass()); // Add your Class
return list; // retunrs a empty List
}
Upvotes: 0