【问题标题】:mvc 5 asp.net identity role and users, how to lest both in order user with it's roles and removemvc 5 asp.net 身份角色和用户,如何避免同时使用它的角色来订购用户并删除
【发布时间】:2016-11-19 04:31:18
【问题描述】:

这里的系统就像一个用户可能有很多角色所以现在我可以列出用户,但我也想列出角色例如

这个控制器将只列出用户,

public ActionResult listOfRolesForUser()
        {

            RoleManager<IdentityRole> RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(ndb));
            UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(ndb));
            ViewBag.AllUsers = UserManager.Users.ToList();
            return View();

        }

这是视图或 listOfRolesForUser.cshtml

@{
    ViewBag.Title = "listOfRolesForUser";
}

<h2>listOfRolesForUser</h2>
<table border="1">
    <tr>
        <td>User name</td>
        <td>Roles</td>
    </tr>
    @foreach (var item2 in ViewBag.AllUsers)
    {
        <tr>
            <td>@item2.UserName</td>
            <td>here i need to list related role too</td>
        </tr>
    }

</table>

现在我将如何列出:

【问题讨论】:

标签: c# asp.net asp.net-mvc asp.net-mvc-5


【解决方案1】:

要同时检索 UsersRoles,您可以存储这两个列表并传递给视图模型。

public ActionResult Index()
{
    using (var context = new ApplicationDbContext())
    {
        UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));

        var users = UserManager.Users;
        var roles = new List<string>();

        // retrieve roles for each user
        foreach (var user in users)
        {
            string str = "";
            foreach (var role in UserManager.GetRoles(user.Id))
            {
                str = (str == "") ? role.ToString() : str + " - " + role.ToString();
            }
            roles.Add(str);
        }

        var model = new HomeViewModel()
        {
            // create view model with these fields
            users = users.ToList(),
            roles = roles.ToList()
        };
        return View(model);
    }
}

使用视图模型填充表格,在HomeController 中实现Delete 方法并通过ajax 调用导航到Home/Delete url。

@model WebApplication1.Models.HomeViewModel

<h2>listOfRolesForUser</h2>
<table border="1">
    <tr>
        <td>User name</td>
        <td>Roles</td>
        <td>Actions</td>
    </tr>

    @{
        int i = 0;

        foreach (var item in Model.users)
        {
            <tr id="@item.Id">
                <td>@item.UserName</td>
                <td>@Model.roles[i]</td>
                <td>
                    <a href="#" onclick="deleteUser('@item.Id')" id="btnDelete" data-toggle="modal" data-target="#deleteModal" title="Delete">
                        Delete
                    </a>
                </td>
            </tr>
            i++;
        }
    }
</table>

【讨论】:

    猜你喜欢
    • 2017-09-14
    • 1970-01-01
    • 1970-01-01
    • 2014-12-11
    • 1970-01-01
    • 1970-01-01
    • 2017-07-09
    • 1970-01-01
    • 2014-07-22
    相关资源
    最近更新 更多