MVC 4 trying to make a select list of all possible membership roles and then set it to be selected with the role the current user is in

StackOverflow https://stackoverflow.com/questions/15604701

  •  29-03-2022
  •  | 
  •  

Question

Using MVC 4, Entity Framework and Simple membership * NEWB ALERT * Just getting started with scaffolding and CRUD.

In our scenario a user can only have one role (webpages_UsersInRoles table in DB) I have a userProfile domain class but I am updating via viewModel.

My goal is to create a select list in the view which shows all the possible roles. When the view loads, the role that this user has, will be the first selected item in the list (selected selected attribute)

I've never even created a select list from a model or controller so please go easy me!

So far I have the following:

public class EditAdminModelVM
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string UserName { get; set; }

    public IEnumerable<string> UserInRole { get; set; } 
//** I believe the function that returns the list of roles 
a user is in is of type IEnumerable - though I could be wrong. **

    [HiddenInput]
    public int UserId { get; set; }
}

Then in my controller I have:

public ActionResult EditAdmin(int id = 0)
    {
        myDB db = new myDB();

        var viewModel = new EditAdminModelVM();

        var UserRoles = Roles.GetAllRoles();
        SelectList UserRolesList = new SelectList(UserRoles);

        viewModel = db.UserProfiles
             .Where(x => x.UserId == id)
             .Select(x => new EditAdminModelVM
             {
                 FirstName = x.FirstName,
                 LastName = x.LastName,
                 Email = x.Email,
                 UserName = x.UserName,
                 UserId = x.UserId,
                 UserInRoles = Roles.GetRolesForUser(x.UserName)
             }).FirstOrDefault();

        ViewBag.UserRolesList = UserRolesList;
        return View(viewModel);
    }

The problem here is that I get a warning for this line: Roles.GetRolesForUser(x.UserName) which says Cannot implicitly convert type string to Systems.Collections.Generic.List. I tried changing my Model property to type List<> but that results in the same error.

Any help would be appreciated!

Was it helpful?

Solution

You are converting a string[] to a list. This is not possible without some conversion.

try:

UserInRoles = new List(Roles.GetRolesForUser(x.UserName))

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top