c# - 使用 RoleManager ApplicationRole 插入新角色
问题描述
我有一种添加新角色的方法,例如:
public async Task<IActionResult> CreateRole(ApplicationRoleModel model)
{
try
{
foreach (var role in model.RoleList)
{
var roleExists = await _roleManager.RoleExistsAsync(role.Name);
if (roleExists) continue;
var createRole = _roleManager.CreateAsync(role);
}
return Ok();
}
catch (Exception e)
{
return BadRequest();
}
}
如您所见,我使用foreach
子句访问具有IEnumerable
以下内容的模型ApplicationRole
:
public class ApplicationRoleModel : ClaimsToRoleModel
{
public IEnumerable<ApplicationRole> RoleList { get; set; }
}
因此,您可以在 foreach 中看到我可以访问role.Name
of RoleList (ApplicationRole)
,我用邮递员对其进行了测试并且它可以工作,它成功添加了新角色,现在我想创建视图以创建新角色,所以我尝试:
@page
@model Security.Dto.Models.ApplicationRoleModel
<form asp-controller="security" asp-action="CreateRole" method="post">
<h4>Create new Role</h4>
<hr />
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="RoleList.Name">Role Name</label>
<input asp-for="RoleList.Name" class="form-control" />
</div>
<button type="submit" class="btn btn-default">Create</button>
</form>
但是当我尝试编译项目时它返回:
“IEnumerable”不包含“Name”的定义,并且找不到接受“IEnumerable”类型的第一个参数的扩展方法“Name”(您是否缺少 using 指令或程序集引用?)
那么,我怎样才能访问从视图中分配给模型的Name
属性呢?ApplicationRole
问候
注意:我也尝试在我的视图中访问它,例如:
@for(Int32 i = 0; i < this.Model.RoleList.Count; i++ ) {
<div class="form-group">
<label asp-for="RoleList[i].Name">Role Name</label>
<input asp-for="RoleList[i].Name" class="form-control" />
</div>
}
但我得到:
无法使用 [] 将索引应用于“IEnumerable”类型的表达式
解决方案
您视图中的模型是,IEnumerable<ApplicationRole>
但您尝试为单个实例创建控件ApplicationRole
您可以在模型中使用List<ApplicationRole>
而不是IEnumerable<ApplicationRole>
使用 jquery 添加角色列表,如下所示
模型:
public class ApplicationRoleModel : ClaimsToRoleModel
{
public List<ApplicationRole> RoleList { get; set; }
}
看法:
@page
@model Security.Dto.Models.ApplicationRoleModel
<form asp-controller="security" asp-action="CreateRole" method="post">
<h4>Create new Role</h4>
<hr />
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group" id="item-list">
<label>Role Name</label>
<input asp-for="RoleList[0].Name" class="form-control items" />
</div>
<a href="#" id="add">Add another</a>//click to add
<br />
<button type="submit" class="btn btn-default">Create</button>
</form>
@section Scripts {
<script>
$(function () {
$("#add").click(function (e) {
e.preventDefault();
var i = ($(".items").length);
var n = '<input class="form-control items" name="RoleList[' + i + '].Name" />'
$("#item-list").append(n);
});
});
</script>
}
推荐阅读
- python - 安全提示 Paypal
- php - ACF 滑块与每个帖子循环
- mysql - 在 mysql 中,如果我有一个列(名称 VARCHAR(5))并且我正在插入一个超过 5 个字符的字符串,它正在工作。但是如何?
- javascript - 如何进一步模块化快递路线?
- python - 使用 tkinter 类导入错误 Python 3
- c++ - 带有空子序列的 std::search
- flutter - 在点击 TextFormField 后可见前缀文本,否则为空白
- ios - 有没有办法重写函数或函数的 .option?
- python - 我无法更新变量的值
- javascript - 如何让按钮出现在列表项旁边?