2

I have a controller

 public ActionResult UsersInRoles()
    {           
        using (var ctx1 = new UsersModel())
        {
            var model = new UsersInRolesViewModel();
            model.UserProfiles = ctx1.UserProfiles.ToList();
            model.UserRoles = ctx1.UserRoles.ToList();
            return View(model);
        }            
    }

I am Passing both of those models through to my View: UserRoles Contains all of my possible roles in the system. Now I need to get an array in my controller of all the roles that a User Is registered for, and pass that through to me view as well, So that I can know not to display roles in a box of available roles which the user is already registered for.

How can I do this?

I see two options:

Some how using linq statement to try and get the data in one go, or To pass the full model of roles through and and array of roles that the user is registered for and then I am able to display either or etc in the view?

AUX Classes related to the Usermodel:

 public class UsersModel : DbContext
{
    public UsersModel()
        : base("name=UsersConnection")
    {}
    public DbSet<UserProfile> UserProfiles { get; set; }
    public DbSet<Roles> UserRoles { get; set; }
    public DbSet<UsersInRoles> UsersInUserRoles { get; set; }
}

and

  public class UsersInRolesViewModel
{
    public IList<UserProfile> UserProfiles { get; set; }
    public IList<Roles> UserRoles { get; set; }
    public IList<ut_GMUTempData> GMUTempData { get; set; }
}
Zapnologica
  • 22,170
  • 44
  • 158
  • 253

2 Answers2

0

This is a recurring question.

Look at my answer to this SO question: Getting values of check-box from formcollection in asp.net mvc

If that's not clear enough, please, leave a comment.

Community
  • 1
  • 1
JotaBe
  • 38,030
  • 8
  • 98
  • 117
0

If you just need roles of the logged in user and you use the default simple membership of Internet Application template, you doesn't need model binding at all. You can retrieve roles of the logged in user in your view like the following:

@{
    // r will be a string[] array that contains all roles of the current user.
    var r = Roles.GetRolesForUser();         
}

and if you want to retrieve roles of any other user, just put the username into that method:

@{
    // r will be a string[] array that contains all roles of the entered username.
    var r = Roles.GetRolesForUser("username"); 
}

in this case, you just need to send the username to your model.

Update:

And if you have UserID, you can retrieve username as the following:

@{
    SimpleMembershipProvider provider = new SimpleMembershipProvider();
    string uname = provider.GetUserNameFromId(id);

    // r will be a string[] array that contains all roles of the entered username.
    var r = Roles.GetRolesForUser(uname); 
}
Amin Saqi
  • 18,549
  • 7
  • 50
  • 70