【发布时间】:2019-04-12 13:18:01
【问题描述】:
我有一种添加新角色的方法,例如:
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中看到我可以访问RoleList (ApplicationRole)的role.Name,我用邮递员测试它并且它有效,它成功添加了新角色,现在我想创建视图来创建新角色所以邮递员我试试:
@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' 并且没有扩展方法 'Name' 接受第一个参数 可以找到类型“IEnumerable”(您是否缺少 使用指令还是程序集引用?)
那么,我如何访问ApplicationRole 的Name 属性以从视图分配给模型?问候
注意:我也尝试在我的视图中访问它,例如:
@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'
【问题讨论】:
-
RoleList.[ToList()|ToArray()]首先。指数。您不能索引IEnumerable -
我不明白你的回答,你能解释一下吗?在我看来,我尝试使用
RoleList.[ToList()|ToArray()]作为您的评论,但它不起作用@dcg -
不,
.[ToList()|ToArray()]表示您使用.ToList()或.ToArray()。之后你就可以索引了。
标签: c# asp.net asp.net-web-api asp.net-core .net-core