问题
I'm pretty new to blazor and have gotten myself in some doubt on adding roles to the database. I have implemented to Identity role management and have a working system. But now i want to add new roles trough the GUI instead of editing the database.
I have a razor page called RolesOverview.razor On this page i have a input field and a button. When i click this button i want to add the text to the roles manager and save it to the database.
This is my razor component
@page "/admin/roles"
@using Microsoft.AspNetCore.Identity
@inject RoleManager<IdentityRole> roleManager
<div class="jumbotron">
<!-- Roles Overview Group Box -->
<div class="row mb-5">
<div class="col-12">
<h1 class="display-6">Roles Options</h1>
<hr class="my-4" />
<div class="row" style="background-color:white; margin-bottom:10px; margin-top:10px;">
<div class="col-12">
<div class="card w-100 mb-3" style="min-width:100%;">
<div class="card-body">
<h5 class="card-title">Roles</h5>
<p class="card-text">
<div class="row">
<div class="col-1">
Role Name:
</div>
<div class="col-10">
<input type="text" style="min-width:100%;" placeholder="Role Type" />
</div>
<div class="col-1">
<a href="#!" class="btn btn-primary" style="min-width:90px;">Add Role</a>
</div>
</div>
</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Not Getting Saved...
@code {
private string CurrentValue { get; set; }
private async void AddRole()
{
if (CurrentValue != string.Empty)
{
if (!await roleManager.RoleExistsAsync(CurrentValue))
{
await roleManager.CreateAsync(new IdentityRole
{
Name = CurrentValue
});
}
}
}
}
I have no clue on what todo next. I's it posible todo it with razor component or do i need to do it trough razor page?
Example would be perfect.
Regards Me!
回答1:
Answer :
<div class="col-10">
<input value="@CurrentValue" @onchange="@((ChangeEventArgs __e) => CurrentValue =__e.Value.ToString())" />
@*<input type="text" style="min-width:100%;" placeholder="Role Type" />*@
</div>
<div class="col-1">
<a @onclick="AddRole" class="btn btn-primary" style="min-width:90px;">Add Role</a>
</div>
@code { private string CurrentValue { get; set; }
private async void AddRole()
{
if (CurrentValue != string.Empty)
{
if (!await roleManager.RoleExistsAsync(CurrentValue))
{
await roleManager.CreateAsync(new IdentityRole
{
Name = CurrentValue
});
}
}
}
}
回答2:
You can use RoleManager to create a new role by using the CreateAsync method:
if (!await roleMgr.RoleExistsAsync("RoleName"))
{
await roleManager.CreateAsync(new IdentityRole
{
Name = "RoleName"
});
}
来源:https://stackoverflow.com/questions/63172239/blazor-role-management-add-role-trough-ui-crud