首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在MVC-4 C#中单击Role,列出具有特定角色的用户

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

Stack Overflow用户
提问于 2019-03-12 02:14:55
回答 1查看 102关注 0票数 1

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

代码语言:javascript
复制
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; }
  }

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

代码语言:javascript
复制
//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);
    }
}

该视图显示保存的所有角色的列表,其中包含编辑、删除和列出该特定角色的链接。

代码语言:javascript
复制
@{
    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>

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

代码语言:javascript
复制
@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>
}

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

EN

回答 1

Stack Overflow用户

发布于 2019-03-12 05:03:42

添加新模型UsersGroups

代码语言:javascript
复制
 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; }
}

添加新控制器UsersGroupController

代码语言:javascript
复制
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);
    }
}

不要忘记更改到您的连接的连接

添加索引视图

代码语言:javascript
复制
@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>

添加更新视图

代码语言:javascript
复制
@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>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55107989

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档