通过单击MVC-4 C#中的角色,列出具有特定角色的用户

时间:2019-03-11 18:14:55

标签: c# asp.net-mvc model-view-controller

如何列出已分配给角色的所有用户。这是我的模特。

namespace Comtrex_ICU.Models
{
  public class UsersContext : DbContext
  {
    public UsersContext()
      : base("DefaultConnection")
    {
    }

    public DbSet<UserProfile> UserProfiles { get; set; }
    public DbSet<Membership> Membership { get; set; }
    public DbSet<Role> Roles { get; set; }
  }

  [Table("UserProfile")]
  public class UserProfile
  {
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
    public string Email { get; set; }
  }

  [Table("webpages_Roles")]
  public class Role
  {
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int RoleId { get; set; }
    public string RoleName { get; set; }
  }

到目前为止,这是我的控制器:当我单击该角色时,它确实会返回一个在该视图中具有该角色正确名称的视图:

//List all users for a role
[HttpGet]

public ActionResult List(string UserName, string RoleName)
{
    using (UsersContext db = new UsersContext())
    {
        var roleSelect = db.Roles.Where(r => r.RoleName.Equals(RoleName)).FirstOrDefault();

        return View(roleSelect);
    }
}

此视图显示所有已保存角色的列表,以及用于编辑,删除和列出该特定角色的链接。

@{
    ViewBag.Title = "RoleIndex";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="spacerBody">
    <h2 class="admin-home-link">@Html.ActionLink("Roles", "AdminIndex")</h2>
    @Html.ActionLink("Create New Role", "RoleCreate") | 
    @Html.ActionLink("Manage User Roles", "RoleAddToUser") 
    <p>&nbsp;</p>
    <div>


        @foreach (string s in Model)
        {

            <div id="userRolesList">
                <p class="role-p">
                    @s
                |<span onclick="return confirm('Are you sure to delete?')">
                   <a href="/Account/RoleDelete?RoleName=@s" 
                 class="delLink"> <span style="color: #f05322">Delete</span> 
                 </a>
                 </span>
                |<a href="/Account/Edit?RoleName=@s">Edit</a>   
                |<a href="/Account/List?RoleName=@s">List</a>

                </p>
            </div>
            <div>

            </div>

        }
    </div>
</div>

然后,当我单击列表链接时,将带我到该视图:

@model Comtrex_ICU.Models.Role
@{
    ViewBag.Title = "List";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2 class="admin-home-link">@Html.ActionLink("List", "AdminIndex")</h2>

<hr/>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    @Html.HiddenFor(m => m.RoleId)





    <p>
        @Model.RoleName
    </p>
}

我将如何列出与正确角色相对应的特定用户?

1 个答案:

答案 0 :(得分:1)

添加新的模型用户组

 public class UsersGroups
{
    public string Id { get; set; }
    public string Username { get; set; }
    public string Email { get; set; }
    public string IdRole { get; set; }
    public string Role { get; set; }
}

添加新的Controller UsersGroupController

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Ebdaa2030.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;

public class UsersGroupController : Controller
{
    private Ebdaa2030DBEntities db = new Ebdaa2030DBEntities();
    private ApplicationUserManager _userManager;
    // GET: UsersGroup
    public ActionResult Index()
    {
        var usersWithRoles = (from user in db.AspNetUsers
                              from userRole in user.AspNetRoles
                              join role in db.AspNetRoles on userRole.Id equals
                              role.Id
                              select new UsersGroups()
                              {
                                  Id = user.Id,
                                  Username = user.UserName,
                                  Email = user.Email,
                                  Role = role.Name,
                                  IdRole = role.Id
                              }).ToList();
        return View(usersWithRoles);
    }

    public ApplicationUserManager UserManager
    {
        get
        {
            return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
        private set
        {
            _userManager = value;
        }
    }
    // GET: Users/Edit/5
    public ActionResult Edit(string id)
    {
        ViewBag.UserType = new SelectList(db.AspNetRoles.ToList(), "Name", "Name");
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public virtual ActionResult Edit(AspNetUser user, string role)
    {
        if (ModelState.IsValid)
        {
            ViewBag.UserType = new SelectList(db.AspNetRoles.ToList(), "Name", "Name");
            var oldUser = db.AspNetUsers.SingleOrDefault(u => u.Id == user.Id);
            var oldRoleId = oldUser.AspNetRoles.SingleOrDefault().Id;
            var oldRoleName = db.AspNetRoles.SingleOrDefault(r => r.Id == oldRoleId).Name;
            if (oldRoleName != role)
            {
                UserManager.RemoveFromRole(user.Id, oldRoleName);
                UserManager.AddToRole(user.Id, user.UserType);
            }
            UserManager.AddToRoleAsync(user.Id, user.UserType);

            return RedirectToAction("Index");
        }
        return View(user);
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
}

别忘了将连接更改为您的连接

添加索引视图

@model IEnumerable<Ebdaa2030.Models.UsersGroups>

@{
       Layout = "~/Views/Shared/_Layout ControlME.cshtml";
}

<div class="row text-center">
    <div class="container-fluid">
        <div class="card-header">
            <i class="fa fa-table"></i> <b>Rols</b>
        </div>
        <br />
        <div class="card-body">
            <div class="table-responsive text-black">
                <table class="table table-bordered table-hover w-100 text-center" id="dataTable" cellspacing="0">
                    <thead>
                        <tr>
                            <th>
                                User Name
                            </th>
                            <th>
                                Email
                            </th>
                            <th>
                                Role
                            </th>
                            <th>Tools</th>
                        </tr>
                    </thead>

                    @foreach (var user in Model)
                    {
                        <tr>
                            <td>
                                @Html.DisplayFor(Model => user.Username)
                            </td>
                            <td>
                                @Html.DisplayFor(Model => user.Email)
                            </td>
                            <td>
                                @Html.DisplayFor(Model => user.Role)
                            </td>
                            <td>
                                <a class="btn btn-success" href="@Url.Action("Edit", "UsersGroup", new { id = user.Id })">
                                    <i class="fa fa-edit "></i>
                                </a>

                            </td>
                        </tr>
                    }
                </table>
            </div>
            <div class="container-fluid">
                <div class="alert alert-success">
                    <label>Count </label>&emsp; @Model.Count()
                </div>
            </div>
            <br />
        </div>
    </div>
</div>

添加更新视图

@model Ebdaa2030.Models.UsersGroups
@{
    Layout = "~/Views/Shared/_Layout ControlME.cshtml";
}

<div class="row text-center">
    <div class="container-fluid">
        <div class="card-header">
            <i class="fa fa-table"></i> <b>Rols</b>
        </div>
        <br />
        <div class="card-body">
            @using (Html.BeginForm())
            {
                @Html.AntiForgeryToken()
            <div class="form-horizontal">
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                @Html.HiddenFor(Model => Model.Id)

                <div class="form-group">
                    <label class="col-md-2 control-label "> <b> Role</b></label>
                    <div class="col-md-5">
                        @Html.DropDownList("UserType", null, new { @id = "role", @class = "form-control" })
                    </div>
                </div>
                <div class="input-group col-md-offset-2 col-md-3">
                    <div class="input-group-append ">
                        <button type="submit" class="btn btn-success"> Update</button>
                        @Html.ActionLink("Back", "Index", "UsersGroup", null, new { @class = "btn btn-primary" })
                    </div>
                </div>
            </div>
            }

        </div>
    </div>
</div>