2

我正在努力想办法弄清楚这应该很简单......

我想获取所有用户的列表,在 <.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>

我尝试了以下方法:

抛出异常Page()后返回OnPostGetRolesAsync()

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

@foreach (ApplicationUser au in Model.UserList)

我猜是因为OnGet没有运行并且UserListnull

如果我将其更改为RedirectToPage()thenOnGet被解雇并将 UserRoleList 设置为一个新列表,我们将回到第一方

尝试打开页面时,从中删除将引发相同的异常(但对于UserRoleList = new List<string>(); UserRoleList )OnGet

干杯

4

1 回答 1

4

您在 Get 中加载 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();
    }
于 2017-12-19T09:25:43.260 回答