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

时间:2017-12-18 23:24:45

标签: c# razor asp.net-core-2.0 razorengine razor-pages

我试图弄清楚这一点,我应该很简单......

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

我尝试过以下方法:

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

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

@foreach (ApplicationUser au in Model.UserList)

我猜是因为OnGet没有投放,而UserListnull

如果我将其更改为RedirectToPage(),那么OnGet会被触发并将UserRoleList设置为新的列表,我们将重新回到原点

删除UserRoleList = new List<string>(); 来自OnGet的尝试在尝试打开页面时会抛出相同的异常(但对于UserRoleList)

欢呼声

1 个答案:

答案 0 :(得分:2)

您在Get中加载UserList但是您必须再次为post请求加载它

    DECLARE
       count_var   NUMBER;
    BEGIN
       SELECT COUNT (*)
         INTO count_var
         FROM not_much_stuff
        WHERE n = -1;

       IF count_var = 0
       THEN
          DBMS_OUTPUT.put_line ('No rows found!');
       ELSIF count_var > 1
       THEN
          DBMS_OUTPUT.put_line ('Too many rows found!');
       ELSE
          DBMS_OUTPUT.put_line ('One row exists!');
       END IF;
    END;