Razor Page Net Core 2.0 - Post 后保留数据

Razor Page Net Core 2.0 - Preserve Data after Post

我绞尽脑汁想弄明白这应该很简单...

我想获取所有用户的列表,select <.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();
        }
    }

这是剃刀页面

        <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>

我试过以下方法:

return Page() after OnPostGetRolesAsync() 抛出异常

NullReferenceException: 对象引用未设置到对象的实例。

@foreach (ApplicationUser au in Model.UserList)

我猜是因为 OnGet 不是 运行 而 UserListnull

如果我将其更改为 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();
    }