Fatikhan Gasimov
Fatikhan Gasimov

Reputation: 943

create user with more than one role in asp.net identity

i am trying to create user with more than one role Here is my viewModel for new user

 public class UserForNewViewModel
    {
        public RegisterViewModel User { get; set; }
        public List<IdentityRole> Roles { get; set; }
    }

Here is my action

 [HttpGet]
    public async Task<ActionResult> Create()
    {
        var roles = await _context.Roles.ToListAsync();
        var model = new UserForNewViewModel()
        {
            Roles = roles
        };
        return View(model);
    }

In view how can i do with multi roles

<div class="form-group">
            <label>Roles</label>
            ???????????????????????????????????
            @Html.DropDownListFor(x => x.Roles., new SelectList(Model.Roles, "Id", "Name"), ("Seçin..."), new { @class = "form-control", id = "ParentId" })
        </div>

enter image description here

Upvotes: 0

Views: 1604

Answers (2)

user5660940
user5660940

Reputation:

you can do it with checkboxes for example

 <div class="col-md-10">
            @foreach (var item in (SelectList)ViewBag.RoleId)
            {
                <input type="checkbox" name="SelectedRoles"
                       value="@item.Value" class="checkbox-inline" />
                @Html.Label(item.Value, new { @class = "control-label" })
            }
        </div>

Upvotes: 0

Munis Isazade
Munis Isazade

Reputation: 23

I have requirement to add multiple user roles for a particular user in user creation phase.

So I'm going to achieve this using checkboxes in front end

so this the viewpage

@model project_name.Models.RegisterViewModel

@{

}

@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal"}))
{

        <div class="form-group">
            <label class="col-md-2 control-label">
                Select User Role
            </label>
            <div class="col-md-10">
                @foreach (var item in (SelectList)ViewBag.RoleId)
                {
                    <input type="checkbox" name="SelectedRoles"
                           value="@item.Value" class="checkbox-inline" />
                    @Html.Label(item.Value, new { @class = "control-label" })
                }
            </div>
        </div>

            ....

            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" class="btn btn-default" value="Register" />
                </div>
            </div>
}

these are the changes I did over existing AspNet Identity 2.0 framework in App_Start folder => IdentityConfig.cs file

    public class RoleManager<TRole> : RoleManager<TRole, string> where TRole : class, IRole<string>
    {
        //
        // Summary:
        //     Constructor
        //
        // Parameters:
        //   store:
        public RoleManager(IRoleStore<TRole, string> store);
    }

       public class ApplicationRoleManager : RoleManager<ApplicationRole>
        {
            public ApplicationRoleManager(
                IRoleStore<ApplicationRole, string> roleStore)
                : base(roleStore)
            {
            }
            public static ApplicationRoleManager Create(
                IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
            {
                return new ApplicationRoleManager(
                    new RoleStore<ApplicationRole>(context.Get<ApplicationDbContext>()));
            }
     }

these are the changes I did over existing AspNet Identity 2.0 framework in Models folder => IdentityModels.cs file

    public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(
        UserManager<ApplicationUser> manager)
    {
        var userIdentity = await manager.CreateIdentityAsync(
            this, DefaultAuthenticationTypes.ApplicationCookie);
        return userIdentity;
    }
}

   public class ApplicationRole : IdentityRole
    {
        public ApplicationRole() : base() { }
        public ApplicationRole(string name) : base(name) { }
        public string Description { get; set; }
    }

So then I've set up controller's register method as follows

   // POST: /Account/Register
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model, HttpPostedFileBase upload, params string[] selectedRoles)
    {

        try
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = model.UserName, Email = model.Email };                      


                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    //Add User to the selected Roles 
                    if (selectedRoles != null)
                    {
                        var addroles = await UserManager.AddToRolesAsync(user.Id, selectedRoles);
                        if (!addroles.Succeeded)
                        {
                            ModelState.AddModelError("", result.Errors.First());
                            ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync("Name", "Name"));
                            return View();
                        }
                    }

                }

                else
                {
                    ModelState.AddModelError("", result.Errors.First());
                    ViewBag.RoleId = new SelectList(RoleManager.Roles, "Name", "Name");
                    return View();
                }

                return RedirectToAction("Index");
                // AddErrors(result);
            }

        }

        // If we got this far, something failed, redisplay form
        catch (RetryLimitExceededException /* dex */)
        {
            //Log the error (uncomment dex variable name and add a line here to write a log.
            ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
        }

        ViewBag.RoleId = new SelectList(RoleManager.Roles, "Name", "Name");

        return View(model);
    }

but each line of above controller that exist 'RoleManager' word I'm getting compile time error as below

Using the generic type 'RoleManager TRole, TKey' requires 2 type arguments

which means I'm getting 3 compile time errors in above method.

Also I followed this reference to get the idea to assign multiple roles for a user in aspnet idenity


EDIT:

I just changed IdentityRole.cs[MetaData] and IdentityUserRole[MetaData] also as follows

namespace Microsoft.AspNet.Identity.EntityFramework
{
    //
    // Summary:
    //     Represents a Role entity

    public class IdentityRole : IdentityRole<string, IdentityUserRole>
    {
        //
        // Summary:
        //     Constructor
        public IdentityRole();
        //
        // Summary:
        //     Constructor
        //
        // Parameters:
        //   roleName:
        public IdentityRole(string roleName);
    }   

public class IdentityRole<TKey, TUserRole> : IRole<TKey>
where TUserRole : IdentityUserRole<TKey>
{
    public TKey Id
    {
        get
        {
            return JustDecompileGenerated_get_Id();
        }
        set
        {
            JustDecompileGenerated_set_Id(value);
        }
    }
    public string Name
    {
        get;
        set;
    }
    public ICollection<TUserRole> Users
    {
        get
        {
            return JustDecompileGenerated_get_Users();
        }
        set
        {
            JustDecompileGenerated_set_Users(value);
        }
    }
    public IdentityRole()
    {
        this.Users = new List<TUserRole>();
    }
}

public class IdentityUserRole<TKey>
{
    public virtual TKey RoleId
    {
        get;
        set;
    }
    public virtual TKey UserId
    {
        get;
        set;
    }
    public IdentityUserRole()
    {
    }
}
}

Upvotes: 2

Related Questions