加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 如何在asp.net mvc4应用程序中显示注册用户列表

发布时间:2020-12-16 04:10:52 所属栏目:asp.Net 来源:网络整理
导读:我使用razor引擎创建了asp.net mvc4应用程序,我对这项技术不熟悉,并尝试找出一种在管理员登录后向管理员显示注册用户列表的方法.成员资格使用system.web.providers.谁能说 – 首先,如何使用实体框架为用户创建单独的角色 其次,如何获取并向管理员显示具有不
我使用razor引擎创建了asp.net mvc4应用程序,我对这项技术不熟悉,并尝试找出一种在管理员登录后向管理员显示注册用户列表的方法.成员资格使用system.web.providers.谁能说 –
首先,如何使用实体框架为用户创建单独的角色
其次,如何获取并向管理员显示具有不同角色的所有注册用户的列表.

提前致谢.
问候

解决方法

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

并在视图中:

@using MvcApplication1.Models
@model IEnumerable<UserProfile>
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <h2>Users list</h2>
    <table>
        <thead>
            <tr>
                <th>id</th>
                <th>name</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var user in Model)
            {
                <tr>
                    <td>@user.UserId</td>
                    <td>@user.UserName</td>
                </tr>
            }
        </tbody>
    </table>
</body>
</html>

当然,为了能够访问/ users / index控制器操作,您需要首先拥有用户和角色.只有Admin角色的用户才能调用它.

这是一个tutorial,它解释了如何使用迁移来为某些帐户播种数据库.

以下是示例迁移配置的外观:

internal sealed class Configuration : DbMigrationsConfiguration<UsersContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
    }

    protected override void Seed(UsersContext context)
    {
        WebSecurity.InitializeDatabaseConnection(
            "DefaultConnection","UserProfile","UserId","UserName",autoCreateTables: true
        );

        if (!Roles.RoleExists("Admin"))
        {
            Roles.CreateRole("Admin");
        }

        if (!WebSecurity.UserExists("john"))
        {
            WebSecurity.CreateUserAndAccount("john","secret");
        }

        if (!Roles.GetRolesForUser("john").Contains("Admin"))
        {
            Roles.AddUsersToRoles(new[] { "john" },new[] { "Admin" });
        }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读