【问题标题】:List The Users in a specific Role by clicking on role in MVC-4 C#通过单击 MVC-4 C# 中的角色列出特定角色中的用户
【发布时间】:2019-03-12 05:03:42
【问题描述】:

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

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

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

【问题讨论】:

  • 我认为这就是Membership 的用途,尽管您没有展示该模型。如果是这样,您将使用您的角色条件对其进行查询,加入以获取详细信息并返回结果。

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


【解决方案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; }
}

添加新控制器用户组控制器

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>

【讨论】:

    猜你喜欢
    • 2013-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-01
    • 2016-12-03
    • 2017-09-10
    • 1970-01-01
    相关资源
    最近更新 更多