Razor Page Net Core 2.0 - 发布后保留数据

问题描述 投票:0回答:1

我正试图弄清楚这应该是简单的......

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

我尝试过以下方法:

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

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

@foreach(Model.UserList中的ApplicationUser au)

我猜是因为OnGet没有运行而且UserList为空

如果我将其更改为RedirectToPage()然后OnGet被触发并将UserRoleList设置为一个新列表,我们回到正方形

删除UserRoleList = new List();在尝试打开页面时,OnGet将抛出相同的异常(但对于UserRoleList)

干杯

c# razor asp.net-core-2.0 razorengine razor-pages
1个回答
1
投票

您在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();
    }
© www.soinside.com 2019 - 2024. All rights reserved.