我正在绞尽脑汁试图弄清楚这应该很简单......
我想获取所有用户的列表,在 <.select> 中选择一个,按一个按钮,获取该用户已分配的所有角色,这就是失败的地方,这是代码
public class RoleManagementModel : PageModel
{
private readonly RoleManager<ApplicationRole> _roleManager;
private readonly UserManager<ApplicationUser> _userManager;
public RoleManagementModel(RoleManager<ApplicationRole> roleManager,
UserManager<ApplicationUser> userManager)
{
_roleManager = roleManager;
_userManager = userManager;
}
[BindProperty]
public InputModel Input { get; set; }
public IList<ApplicationUser> UserList { get; set; }
public IList<string> UserRoleList { get; set; }
public IList<string> RoleList { get; set; }
public class InputModel
{
public string User { get; set; }
public string RoleToRemove { get; set; }
public string RoleToAdd { get; set; }
}
public async Task<IActionResult> OnGetAsync()
{
UserList = _userManager.Users.ToList();
UserRoleList = new List<string>();
RoleList = new List<string>();
return Page();
}
public async Task<IActionResult> OnPostGetRolesAsync()
{
var user = await _userManager.FindByNameAsync(Input.User);
UserRoleList = await _userManager.GetRolesAsync(user);
return Page();
}
}
这是 Razor 页面
<select asp-for="Input.User" class="..">
@foreach (ApplicationUser au in Model.UserList)
{
<option>@au.UserName</option>
}
</select>
<button class=".." type="submit" asp-page-handler="GetRoles">Get Roles </button>
<select asp-for="Input.RoleToRemove" class="..">
@foreach (string ur in Model.UserRoleList)
{
<option>@ur</option>
}
</select>
我尝试过以下方法:
返回Page()
之后OnPostGetRolesAsync()
抛出异常
NullReferenceException:未将对象引用设置为对象的实例。
@foreach (ApplicationUser au in Model.UserList)
我猜是因为OnGet
未运行且 UserList
是 null
如果我将其更改为 RedirectToPage()
然后OnGet
被解雇并将 UserRoleList 设置为新列表,我们回到原点
正在删除UserRoleList = new List<string>();
来自OnGet
尝试打开页面时会抛出相同的异常(但对于 UserRoleList)
干杯
最佳答案
您在 Get 中加载了 UserList,但必须为 post 请求再次加载它
public async Task<IActionResult> OnGetAsync()
{
UserList = _userManager.Users.ToList();
UserRoleList = new List<string>();
RoleList = new List<string>();
return Page();
}
public async Task<IActionResult> OnPostGetRolesAsync()
{
UserList = _userManager.Users.ToList(); // You have to reload
var user = await _userManager.FindByNameAsync(Input.User);
UserRoleList = await _userManager.GetRolesAsync(user);
return Page();
}
关于c# - Razor Page Net Core 2.0 - 发布后保留数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47877910/