Search code examples
c#asp.net-mvcasp.net-identity-2

Multiple object sets per type are not supported when i create a dropdown list


when i create a dropdown list in identity tabel AspNetRole with this code

IdentityConfig.cs

public class ApplicationRoleManager : RoleManager<IdentityRole>
{
    public ApplicationRoleManager(IRoleStore<IdentityRole, string> roleStore)
        : base(roleStore)
    {
    }

    public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
    {
        return new ApplicationRoleManager(new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>()));
    }
}

Startup.Auth.cs:

app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

.

.private ApplicationRoleManager _roleManager;
public ApplicationRoleManager RoleManager
{
    get
    {
        return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
    }
    private set
    {
        _roleManager = value;
    }
}

controller :

        [AllowAnonymous]
    public ActionResult Register()
    {
        ViewBag.name = new SelectList(db.Roles, "RoleID", "RoleName");

        return View();
    }

View :

<div class="form-group">
    <label>نقش</label>
    <div class="col-md-10">
      @Html.DropDownList("name", null, htmlAttributes: new { @class = "form-control" })
    </div>
</div>

it show me this error :

enter image description here

How can i solve that ?

/************************************************************************************************/


Solution

  • Controller

    [AllowAnonymous]
    public ActionResult Register() {
        ViewBag.Roles = new SelectList(db.Roles.ToList(), "Id", "Name");
    
        return View();
    }
    

    OR

    [AllowAnonymous]
    public ActionResult Register() {
        var roles = db.Roles.Select(r => new { RoleID = r.Id, RoleName = r.Name}).ToList();
        ViewBag.Roles = new SelectList(roles, "RoleID", "RoleName");
    
        return View();
    }
    

    View :

    <div class="form-group">
        <label>نقش</label>
        <div class="col-md-10">
          @Html.DropDownList("SelectedRole", (IEnumerable<SelectListItem>)ViewBag.Roles, htmlAttributes: new { @class = "form-control" })
        </div>
    </div>