【问题标题】:Finding Roles MVC 4 Simple Membership查找角色 MVC 4 简单成员
【发布时间】:2013-08-27 17:27:16
【问题描述】:

我的行动

[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[]

【问题讨论】:

  • 显示它有什么问题?你不知道如何在视图中做到这一点或什么?
  • 不知道如何进入角色.. 用户配置文件没有角色属性.. 我感觉很愚蠢,不知道为什么我粘贴了这段代码......只是想知道如何进入角色和在 Simple Membership 中使用用户名显示他们

标签: asp.net-mvc simplemembership


【解决方案1】:

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

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

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

【讨论】:

  • System.String[] 我有这个输出...我认为有一些转换问题...我更新了问题..
  • 因为这些是角色,而不是一个角色,所以您必须遍历它们以获取用户分配给的所有角色
  • 使用 foreach 循环 stackoverflow.com/questions/4463000/razor-syntax-foreach-loop 但访问数组中的第一个元素应该没问题
  • 我知道在哪里添加循环......?
  • 你可以把它放在你需要的地方
猜你喜欢
  • 1970-01-01
  • 2012-02-19
  • 1970-01-01
  • 1970-01-01
  • 2013-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-11
相关资源
最近更新 更多