寻找角色MVC 4简单会员

时间:2013-08-24 21:57:56

标签: asp.net-mvc simplemembership

我的行动

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

我想用UserId和UserName显示角色我该怎么办?

更新: 查看模型

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

查看

@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>
            }

输出是System.String []

1 个答案:

答案 0 :(得分:2)

假设您已在应用程序中启用了角色,并且您已经创建了一些角色:

using WebMatrix.WebData;
///blah blah blah...

///inside some action:
var roles = (SimpleRoleProvider)Roles.Provider;

var allRoles = roles.GetAllRoles();

为特定用户获取角色:

var userRoles = roles.GetRolesForUser("admin@user.com");

回答你的新问题,试试这个:

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)
            };

您正在为已声明的变量分配值,显然数据类型不匹配。