Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 507
Khyati Bhardwaj Avatar asked Oct 03 '12 10:10

Khyati Bhardwaj


1 Answers

[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" });
        }
    }
}
like image 144
Darin Dimitrov Avatar answered Oct 06 '22 00:10

Darin Dimitrov