Search code examples
asp.net-mvcsimplemembership

Finding Roles MVC 4 Simple Membership


My Action

[Authorize(Roles = "Admin")]
public ActionResult Index()
{
    using (var ctx = new _dbContext())
    {
        return View(ctx.UserProfiles.OrderBy(x => x.UserId).ToList());
    }
}

I want to display roles with UserId and UserName how can i do that??

Update: View Model

public class AccountIndexViewModel
{
    public int UserId { get; set; }
    public string UserName { get; set; }
    public string Roles { get; set; }
}

View

@using GoldCalculator.Models
@model IEnumerable<AccountIndexViewModel>
            @foreach (var user in Model)
            {
                <tr>
                    <td>@user.UserId</td>
                    <td>@user.UserName</td>
                    <td>@user.Roles</td>
                    <td> @Html.ActionLink("X", "Delete", new { id = @user.UserName }, new {  @class = "deletebtn"})</td>
                </tr>
            }

The output is System.String[]


Solution

  • Assuming you have enabled roles in your application and that you have already created some roles:

    using WebMatrix.WebData;
    ///blah blah blah...
    
    ///inside some action:
    var roles = (SimpleRoleProvider)Roles.Provider;
    
    var allRoles = roles.GetAllRoles();
    

    Getting role for specific user:

    var userRoles = roles.GetRolesForUser("[email protected]");
    

    Answering you new question, try this:

    var model = ctx.UserProfiles.OrderBy(x => x.UserId);
    var newModel = from ab in model
                select new 
                {
                    UserName = ab.UserName,
                    UserId = ab.UserId,
                    Role = roles.GetRolesForUser(ab.UserName)
                };
    

    You are assigning value to variable that already has been declared and apparently data types don't match.