views:

260

answers:

2

I have an ASP.NET MVC project in C# using Forms Authentication and Active Directory is the Membership Provider (users login with their existing uid/pwd). However, I would like the roles to be supplied by aspnet_Roles (the default table created by the application). In my Web.config I have: with default setting for this node.

I successfully followed the NerdDinner sample application PDF and wish to use what I have learned. In my app I am using the Repository pattern just like NerdDinner. In NerdDinner, it shows how to use a Helper method to populate a DropDownList. I would like to do the same, but instead of countries and DropDown I would like to pull Roles from a table and populate check boxes.

In my UsersController.cs I have:

//
// ViewModel Classes
public class UserFormViewModel
{
    // properties
    public User User { get; private set; }
    public SelectList Roles { get; private set; }

    // Constructor
    public UserFormViewModel(User user)
    {
        User = user;
        Roles = new SelectList(Roles.All, ); //this is where I have problems
    }
}

In my view I have (which of course will not work):

<ul>
    <% foreach (var role in Roles as IEnumerable<SelectListItem>)) { %>
    <li><%= Html.CheckBox(role.ToString())%> <%= role.ToString() %></li>
    <% } %>
</ul>

P.S. I am a newbie to .NET, but I love it! Correct me if I am wrong, but I think this issue has to do with collections and type definitions?

Also, I am familiar with using the ASP.NET configuration tool to add Roles and Users, but I would like to create a custom User Admin section.

A: 

Something like this ?

<li><%= Html.CheckBox(role.ToString(), 
     Roles.IsUserInRole(Model.User.Identity.LoginName, role.ToString())) %> 
    <%= role.ToString() %>
</li>

Cant quite remember the exact syntax of the Roles in the asp.net membership provider, but it is something along those lines.

Morph
Hey Morph I believe it would be: <%= Html.CheckBox(role.ToString(), Roles.IsUserInRole(Model.User.UserName, role.ToString())) %> but how would I start the loop? I am trying: <% foreach (var role in Roles as IEnumerable<ArrayList>) { %>, but that does not work
robnardo
A: 

It looks like I do not need use the UserFormViewModel class. Morph helped me out. This is what I am doing:

<ul>            
    <% 
        string[] allroles = Roles.GetAllRoles();
        foreach (string role in allroles) {
    %>
    <li>
        <%= Html.CheckBox(role.ToString(), Roles.IsUserInRole(Model.UserName, role.ToString())) %>
        <%= role.ToString() %>
    </li>                   
    <% } %>

</ul>
robnardo
this works too: foreach (string role in Roles.GetAllRoles()) { }
robnardo
Ah i see you found out how to do the loop. Yeah roles in a simple string variable :).
Morph