我想弄清楚这应该很简单...
我要获取所有用户的列表,在中选择一个,按一个按钮,获取该用户已分配的所有角色,这就是失败的地方,这里是代码
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();
}
}
这是剃刀页面
<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,但必须为发布请求再次加载UserList
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/