Get Role List from the AspNetRoles table in MVC5

3

I want the default record to create a project in MVC5, under repeat password put a selection list ( ComboBox ) where I show the list of the roles that exist in the table AspNetRoles creates by default the Visual Studio.

I have had problems getting the list of the AspNetRoles , since I do not know what the context is that uses the Idendity , and the select is not created exactly.

  

I just need to know how to get the list in the controller and how   pass it on, the Insert I do not need it.

My Controller:

// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register()
{
    return View();
}

My View:

@model StyleTest.Models.RegisterViewModel
@{
    ViewBag.Title = "Registrarse";
}

<h2>@ViewBag.Title.</h2>

@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()
    <h4>Cree una cuenta nueva.</h4>
    <hr />
    @Html.ValidationSummary("", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" class="btn btn-default" value="Registrarse" />
        </div>
    </div>
}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

My connection in the web.config:

  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=.;Initial Catalog=StyleTest;Integrated Security=True" providerName="System.Data.SqlClient" />
    <add name="StyleTestEntities" connectionString="metadata=res://*/Contexto.StyleTest.csdl|res://*/Contexto.StyleTest.ssdl|res://*/Contexto.StyleTest.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.;initial catalog=StyleTest;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>

Use MVC5 with Visual Studio 2015.

    
asked by ByGroxD 20.04.2017 в 16:31
source

2 answers

1

First the context must be instantiated:

ApplicationDbContext userContext;

Then add this in the register or where you need to:

userContext = new ApplicationDbContext();
var roles = userContext.Roles.ToList();
ViewBag.roles = new SelectList(roles, "Id", "Name");

Finally in your view you should put the following to reflect the data you need:

@Html.DropDownList("roles", ViewBag.roles as IEnumerable<SelectListItem>, null, htmlAttributes: new { @class = "form-control" })

That's it.

    
answered by 28.04.2017 / 16:07
source
3

It's never a bad idea to read the documentation regarding Identity and how it works internally. With this you would know that Identity has its own context relative to the application (ApplicationDbContext) . In fact, if you enable migrations in a project newly generated by VS you will see that it asks to specify to which DbContext you are pointing this migration (this since you can "extend" the properties of IdentityModels). In the official documentation you will see the reasons and why of all this.

First, within your controller you must make certain definitions:

ApplicationDbContext userContext;
private ApplicationUserManager _userManager;

public ApplicationUserManager UserManager
{
get
    {
        return _userManager ??
 HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
        private set
        {
            _userManager = value;
        }
    }

public MiControladorController()
    {
        userContext = new ApplicationDbContext(); 
    }

With this you assign the ApplicationDbContext() to a variable userContext , what do you achieve with this? ... access the Identity API as if it were a common and ordinary DbContext. You can see the classes Roles, Users, etc. and make queries via LINQ that you deem convenient (among them you assign to an enumerable the roles to pass them to your SelectList).

It would be something like that (I get roles / users and user in particular):

var roles = context.Roles.Include(r => r.Users).OrderBy(r => r.Name).AsQueryable();
var user = context.Users.FirstOrDefault(u => u.UserName == userName);

Then to move to SelectList (in this case via ViewBag, use whatever you want, you can even send this data in JSON to exploit them in a front in JS):

ViewBag.RolesDDL = new SelectList(roles, "Id", "Name");

The select that you assign to that ViewBag via Razor will have as value the ID of the role and as option the name of the role.

In your POST method for registration (you'll have to use a viewModel yes or yes to be able to add this new field correctly) you can assign the role as follows:

UserManager.AddToRole(user.Id, nombreRol);

You must use UserManager in order to obtain the user ID, in the initial implementation it is already initialized so you can use them directly.

I have created a NuGet package that generates a controller and views with everything necessary for creating, assigning, editing and deleting roles to different users. It's for MVC5 and the views are for Bootstrap:

link

You install it and it's ready, it can also serve as an example. Greetings.

    
answered by 27.04.2017 в 05:55