c#


How to get name of roles in Views from IdentityUser in asp.net mvc? [duplicate]


This question already has an answer here:
The model item passed into the dictionary is of type .. but this dictionary requires a model item of type
1 answer
I am trying to display a list of Roles in my index view but there seems to be no possible way to access dbo.AspNetRoles??
ROLE MAINTENANCE CONTROLLER:
namespace DwBusService.Controllers
{
public class DwRoleMaintenanceController : Controller
{
// private readonly ApplicationDbContext _context;
private readonly RoleManager<IdentityRole> roleManager;
private readonly UserManager<ApplicationUser> userManager;
public DwRoleMaintenanceController(RoleManager<IdentityRole> roleManager, UserManager<ApplicationUser> userManager)
{
this.roleManager = roleManager;
this.userManager = userManager;
}
// GET: DwRoleMaintenance
public async Task<IActionResult> Index()
{
var roles = roleManager.Roles.OrderBy(a => a.Name);
return View(roles);
}
}
}
APPLICATION USER MODEL
namespace DwBusService.Models
{
// Add profile data for application users by adding properties to the ApplicationUser class
public class ApplicationUser : IdentityUser
{
public ApplicationUser()
{
}
[Display(Name = "Local Authentication")]
public bool LocalAuthentication { get; set; }
}
}
INDEX ROLE MAINTENANCE VIEW
#model IEnumerable<DwBusService.Models.ApplicationUser>
....
<table class="table">
<thead>
<tr>
<th>#Html.DisplayNameFor(model => model.Roles)</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model) {
<tr>
<td>#Html.DisplayFor(modelItem => item.Roles)</td>
<td>
<a asp-action="Edit" asp-route-id="#item.Id">Edit</a> |
<a asp-action="Details" asp-route-id="#item.Id">Details</a>
<a asp-action="Delete" asp-route-id="#item.Id">Delete</a>
</td>
</tr>
}
</tbody>
</table>
I cannot access Roles.Name or Roles.Id from item.Roles. I have tried to create a virtual RoleNavigation property in Application user, I have tried to make my own IdentityRole.cs model, I have tried many things. Can anyone help me? When I run this code as is I get this error:
InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable'1[Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole]', but this ViewDataDictionary instance requires a model item of type 'System.Collections.Generic.IEnumerable'1[DwBusService.Models.ApplicationUser]'.
DBO.ASPNETROLES.SQL
CREATE TABLE [dbo].[AspNetRoles] (
[Id] NVARCHAR (450) NOT NULL,
[ConcurrencyStamp] NVARCHAR (MAX) NULL,
[NormalizedName] NVARCHAR (256) NULL,
CONSTRAINT [PK_AspNetRoles] PRIMARY KEY CLUSTERED ([Id] ASC)
);
GO
CREATE NONCLUSTERED INDEX [RoleNameIndex]
ON [dbo].[AspNetRoles]([NormalizedName] ASC);
Read this first: http://www.c-sharpcorner.com/UploadFile/asmabegam/Asp-Net-mvc-5-security-and-creating-user-role/
If you have done something similar to this then this is what I am doing to get the roles associated with a user plus getting a list of all roles available:
public ActionResult GetRoles(string UserName)
{
if (!string.IsNullOrWhiteSpace(UserName))
{
Models.ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
var account = new AccountController(HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(), null);
ViewBag.RolesForThisUser = account.UserManager.GetRoles(user.Id);
// prepopulate roles for the view dropdown
var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
ViewBag.Roles = list;
}
return View("ManageUserRoles");
}
Maybe this code will give you some ideas :)....I should have created a ViewModel to contain the results...but I lazily used ViewBag instead.
On the View side, here is the code that utilized the list:
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="col-sm-6" >
<h3>Add Role to #Model.UserName</h3>
#Html.Hidden("UserID", Model.Id)
<span style="font-size:large">Role Name:</span> #Html.DropDownList("RoleName", (IEnumerable<SelectListItem>)ViewBag.Roles, "Select ...")
<input class="btn-sm btn-default" type="submit" value="Save" />
</div>

Related Links

create .sql script with Visual Studio 2012 at c# and how run it?
C# win form app not working outside rar file
await async lambda in ActionBlock
cant access child control with FindControl()
How Can I guarantee that the Ninject will call the Disposable() automatically?
Signalr - Join multiple groups
SQL with subqueries to Linq or Criteria C#
How can I write MemoryStream to byte[] [duplicate]
The name 'xxx' does not exist in the current context in WP7
AutoResetEvent.WaitOne() method return value in C#
Site wide global flag that can be set via HTTP
WCF with Windows service hosting for Host and Client
MATLAB NET.ASSEMBLY with C#
Regex help to find a text is not linked in xml
Maintaining UserLog for each user in LAN based Windows Application
Using TCSCConverter from the Word Interop in C#

Categories

HOME
marie
leaflet
snappy
android-ndk
dynamic
readdir
ebay-api
cryengine
okhttp3
servicenow
schema
software-collections
gcloud
adroitlogic
hql
vivado-hls
windows-phone
project-reactor
glibc
descriptor
beaker-notebook
functional-dependencies
apdu
my.cnf
sasl
angular2-changedetection
dynamic-memory-allocation
typeorm
dynamics-ax-2012-r3
opencsv
storefront
scene7
favorites
ponylang
matrix-multiplication
stencyl
google-cloud-powershell
collation
java-5
bzip2
angular-fullstack
anonymous-function
automapper-4
standard-error
htop
hellosign
programming-pearls
totalview
blitz3d
dimensionality-reduction
falcon
weblogic-maven-plugin
nsoperationqueue
diameter-protocol
python-rq
boost-propertytree
joomla3.3
teamwork
tinymce-plugins
valdr-bean-validation
accpac
mathics
crtdbg.h
aiff
diffmerge
mixradio
php-amqplib
lastinsertid
svg-android
google-mirror-api
removeall
latex-suite
nx
generator-expression
blotter
screensharing
teamsystem
certificate-revocation
mvcmailer
win-prolog
clgeocoder
carbon-emacs
file-storage
ihtmldocument2
html-help-workshop

Resources

Encrypt Message