Question

The answer in the following post:

Registration form with roles MVC3, Error: ViewData item is of type "system.sting" must be "IEnumerable<selectlistitem>

Worked for me great. However, how would this change, if I had to assign an user to a list of Asp .Net Roles?

I want to be able to iterate through a list of Roles available and render checkboxes, and how do I see what roles the user is assigned to when they click update from the Model? (I hope this question makes sense).

Thanks in advance.

Was it helpful?

Solution

Ok, I solved it without using the html helpers. I am still looking for an answer with HTML helpers :).

Model

    public class RolesModel
    {
      public string Email { get; set; }
      public string[] Roles { get; set; }
    }

Controller Code To Launch the View

    public Action Result ShowRoles()
    {
      model.Roles = Roles.GetAllRoles();
    }

Razor View

    @foreach (string role in Model.Roles)
    {
      <input type="checkbox" name="Roles" value="@role" checked="@Roles.IsUserInRole(@role)"       />@role
    }

Controller Code To Update the View

    public ActionResult AccountManagement()
    {
      if (Roles.GetRolesForUser().Length > 0 )
        Roles.RemoveUserFromRoles(model.Email, Roles.GetRolesForUser());

      if (model.Roles != null && model.Roles.Length > 0)
        Roles.AddUserToRoles(model.Email, model.Roles);
    }

As always if there is a cleaner/better way of doing it, please let me know.

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