-1

I have been following a tutorial lately, and I am in the phase of add a new role for users.

I would like to add a new role, but the problem is nothing happens after I submitted or added a role. The page just refresh and that' it.

My goal here is just to add a new role and store it to the database.

Controller: RoleManagerController

        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> AddRole(string roleName)
        {
            if (roleName != null)
            {
                await _roleManager.CreateAsync(new IdentityRole(roleName));
            }
            return View();
        }

View: RoleManager/Index.cshtml

@model List<Microsoft.AspNetCore.Identity.IdentityRole>
@{
     ViewBag.Title = "Role Manager";
     Layout = "~/Views/Shared/_Layout.cshtml";

}
<h1>Role Manager</h1>
<form method="post" asp-action="AddRole" asp-controller="RoleManager">
    <div class="input-group">
        <input name="roleName" class="form-control w-25">
        <span class="input-group-btn">
            <button class="btn btn-info">Add New Role</button>
        </span>
    </div>
</form>

Data: ApplicationDBContext.cs

   public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
             : base(options)
        {
        }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            builder.HasDefaultSchema("Identity");
            builder.Entity<IdentityUser>(entity =>
            {
                entity.ToTable(name: "User");
            });
            builder.Entity<IdentityRole>(entity =>
            {
                entity.ToTable(name: "Role");
            });
            builder.Entity<IdentityUserRole<string>>(entity =>
            {
                entity.ToTable("UserRoles");
            });
            builder.Entity<IdentityUserClaim<string>>(entity =>
            {
                entity.ToTable("UserClaims");
            });
            builder.Entity<IdentityUserLogin<string>>(entity =>
            {
                entity.ToTable("UserLogins");
            });
            builder.Entity<IdentityRoleClaim<string>>(entity =>
            {
                entity.ToTable("RoleClaims");
            });
            builder.Entity<IdentityUserToken<string>>(entity =>
            {
                entity.ToTable("UserTokens");
            });
        }

    }
Summer Winter
  • 25
  • 2
  • 6

1 Answers1

1

Instead of passing the Role to the constructor, pass it as the property of IdentityRole class.

    IdentityResult result = await roleManager.CreateAsync( new IdentityRole
                {
                    Name = roleName
                };
);