Search code examples
c#asp.net-mvcmembership

How to check if only one Role is matching?


I need to filter users by Roles, but all users belong to two Roles

Example: Admin and Group1 for one user, and User and Group1 for the other.

Now I want to filter them by Group1 Role and ignore Admin and User.

public ViewResult Index()
{
    string[] roles = Roles.GetRolesForUser();
    var group = string.Join(" ", roles ); 
    group = group.Replace("Admin", "");//Used this to single out Group1 from Admin user
    return View(new UserViewModel
                    {
                        Users = _userService.FindAll().Where(x => Roles.GetRolesForUser(x.UserName).Contains(group)),
                        Roles = roles
                    });
}

This doesn't error out but it shows it empty. I think I know why but still can't figure out how to go around it...


Solution

  • public ViewResult Index()
    {
       var roleFilter = Roles.GetRolesForUser().First(r => !r.equals("Admin"));
    
       return View(new UserViewModel
                    {
                        Users = _userService.FindAll().Where(x => Roles.GetRolesForUser(x.UserName).Contains(roleFilter)),
                        Roles = new [] {roleFilter}
                    });
    }