我有这个工作的RoleController及其视图,其中列出了所有角色
RoleController类:
public class RoleController : Controller
{
RoleManager<IdentityRole> roleManager;
public RoleController(RoleManager<IdentityRole> roleManager)
{
this.roleManager = roleManager;
}
public IActionResult Index()
{
var roles = roleManager.Roles.ToList();
return View(roles);
}
}
索引视图
@model IEnumerable<Microsoft.AspNetCore.Identity.IdentityRole>
@{
ViewData["Title"] = "Index";
}
<h1>List of Roles</h1>
<a asp-action="Create">Create</a>
<table class="table table-striped table-bordered">
<thead>
<tr>
<td>Id</td>
<td>Name</td>
<td></td>
</tr>
</thead>
<tbody>
@foreach (var role in Model)
{
<tr>
<td>@role.Id</td>
<td>@role.Name</td>
<td>
<form asp-action="Delete" asp-route-id="@role.Id" method="post">
<button type="submit" class="btn btn-sm btn-danger">
Delete
</button>
</form>
</td>
</tr>
}
</tbody>
</table>
现在,我想将这些代码迁移到Razor Pages。这就是我创建的:
public class IndexModel : PageModel
{
RoleManager<IdentityRole> roleManager;
public IndexModel(RoleManager<IdentityRole> roleManager)
{
this.roleManager = roleManager;
}
public async Task<IActionResult> OnGetAsync()
{
var roles = await roleManager.Roles.ToListAsync();
return Page();
}
}
在MVC版本中,它将roles
返回到视图。但是对于Razor Pages版本,由于具有模型绑定功能,应该返回什么?
答案 0 :(得分:1)
这是一个工作示例:
Index.cshtml:
@page
@model IndexModel
@{
ViewData["Title"] = "Index";
}
<h1>List of Roles</h1>
<a asp-action="Create">Create</a>
<table class="table table-striped table-bordered">
<thead>
<tr>
<td>Id</td>
<td>Name</td>
<td></td>
</tr>
</thead>
<tbody>
@foreach (var role in Model.roles)
{
<tr>
<td>@role.Id</td>
<td>@role.Name</td>
<td>
<form asp-action="Delete" asp-route-id="@role.Id" method="post">
<button type="submit" class="btn btn-sm btn-danger">
Delete
</button>
</form>
</td>
</tr>
}
</tbody>
</table>
Index.cshtml.cs:
public class IndexModel : PageModel
{
RoleManager<IdentityRole> roleManager;
public IndexModel(RoleManager<IdentityRole> roleManager)
{
this.roleManager = roleManager;
}
public List <IdentityRole> roles { get; set; }
public async Task<IActionResult> OnGetAsync()
{
roles = await roleManager.Roles.ToListAsync();
return Page();
}
}
更新:
Index.cshtml.cs:
namespace IdentityRazor3_1.Pages
{
public class IndexModel : PageModel
{
//...
}
}
Index.cshtml:
@page
@model IdentityRazor3_1.Pages.IndexModel
如果您不想每次都指定相同的名称空间,则可以将以下代码添加到_ViewImports.cshtml
中:
@using IdentityRazor3_1.Pages
或者:
@namespace IdentityRazor3_1.Pages