ASP.NETMVC5GetUsersfromaSpecificRole如何显示特定角色的所有用户的列表。我将一个IdentityRole模型附加到我的视图并为其分配了“管理员”角色。到目前为止,我只能获得UserId。@modelMicrosoft.AspNet.Identity.EntityFramework.IdentityRole@Html.DisplayNameFor(model=>model.Name)//显示'Admin'@foreach(variteminModel.Users){@Html.DisplayFor(modelItem=>item.UserId)}一种可能的解决方案是在控制器中创建用户列表并将其附加到视图。问题是我还需要角色本身的数据。如果您使用的是ASP.NETIdentity2:publicActionResultUserList(stringroleName){varcontext=newApplicationDbContext();varusers=fromuincontext.Userswhereu.Roles.Any(r=>r.Role.Name==roleName)selectu;ViewBag.RoleName=角色名;返回视图(用户);在视图中:@modelMicrosoft.AspNet.Identity.EntityFramework.IdentityUser//或ApplicationUser@Html.DisplayNameFor(model=>ViewBag.RoleName)//显示'Admin'@foreach(Model.Users中的varitem){@Html.DisplayFor(modelItem=>item.Id)@Html.DisplayFor(modelItem=>item.UserName)}我找到了一种使用ViewModels的方法工作解决方案:ViewModel:publicclassRoleUserVM{publicIdentityRoleRole{get;放;}公共ICollection用户{得到;放;}}控制器:publicasyncTaskDetails(stringid){if(id==null){returnnewHttpStatusCodeResult(HttpStatusCode.BadRequest);}varrole=awaitRoleManager.FindByIdAsync(id);变种用户=新列表();foreach(UserManager.Users.ToList()中的varuser){if(等待我们erManager.IsInRoleAsync(user.Id,role.Name)){users.Add(user);}}RoleUserVMvm=newRoleUserVM();vm.Users=用户;vm.Role=角色;返回视图(虚拟机);}查看:以上是C#学习教程:ASP.NETMVC5从特定角色获取用户分享的所有内容。如果对大家有用,需要进一步了解C#学习教程,希望大家多多关注——@modelAspnetIdentitySample.Models。RoleUserVM@Html.DisplayFor(model=>model.Role.Name)@foreach(variteminModel.Users){@Html.DisplayFor(modelItem=>item.UserName)}本文收集自网络,不代表一个位置。侵权请点击维权联系管理员删除如需转载请注明出处:
