how to show list of registered users to admin in asp.net mvc4 application

感情迁移 提交于 2019-12-01 02:27:08

问题


I have created asp.net mvc4 application using razor engine, im new to this technology and trying to figure out a way to display a list of registered users to the admin after admin logs in. Membership is using system.web.providers. can anyone tell- firstly how to create separate roles for users, admin using entity framework secondly how to get and display the list of all registered users with different roles to the admin.

Thanks in advance. Regards


回答1:


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

and in the view:

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

Of course in order to be able to access the /users/index controller action you need to first have users and roles. Only a user in the Admin role will be able to invoke it.

Here's a tutorial which explains how you could use migrations in order to seed your database with some accounts.

Here's how a sample migration configuration might look like:

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


来源:https://stackoverflow.com/questions/12706286/how-to-show-list-of-registered-users-to-admin-in-asp-net-mvc4-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!