【发布时间】:2021-03-19 15:10:55
【问题描述】:
我有 ASP .NET Сore Razor 页面,我在其中填充 select 带有公司部门的 html 列表(在 Ids 转到值时显示名称)。 具体的公司,其Id和部门由Get请求中的输入参数确定(以下示例为 大大简化):
public class MyModel : PageModel
{
private readonly MyDbContext _context;
private readonly UserManager<Employee> _userManager;
public long _companyId;
public Dictionary<long, string> _companyDepartments;
[BindProperty]
public InputModel Input { get; set; }
public string StatusMessage { get; set; }
public class InputModel
{
[Required]
public string Name { get; set; }
[Required]
public long DepartmentId { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
}
public RegisterModel(MyDbContext context)
{
_context = context;
_userManager = userManager;
}
public async Task OnGetAsync(string inviteLink)
{
var company = _context.Companies.SingleOrDefault(c => c.InviteLink == inviteLink);
if (company != null)
{
_companyId = company.Id;
_companyDepartments = _context.Departments.Where(d => d.CompanyId == company.Id).ToDictionary(d => d.Id, d => d.Name);
}
else
StatusMessage = "Invalid inviteLink!";
}
public async Task<IActionResult> OnPostAsync()
{
if (_userManager.FindByEmailAsync(Input.Email).Result != null)
{
//_companyDepartments is already empty here
ModelState.AddModelError(string.Empty, $"Employee with Name {Input.Name} and " +
"in Department '{_companyDepartments[Input.DepartmentId]}' already exists!");
//reloading same page but OnGetAsync is NOT fired and therefore _companyDepartments is NOT filled
return Page();
}
if (ModelState.IsValid)
{
//adding user to database
var user = new Employee
{
Name = Input.Name,
//_companyId is also already empty here
CompanyId = _companyId,
DepartmentId = Input.DepartmentId
};
var result = await _userManager.CreateAsync(user, Input.Password);
...
}
// If we got this far, something failed, redisplay form
return Page();
}
在发布时我执行检查,如果它失败 - 我需要从部门 ID 获取部门名称,但 _companyDepartments 在这里已经是空的。 RegisterModel 构造函数被调用,_companyDepartments 变为空,但 OnGetAsync 之后未触发,因此 _companyDepartments 未填充。
如果检查通过,我需要将用户添加到数据库但 _companyId 那里也已经为空。
之后,我重新加载了相同的页面(顶部有一些额外的 StatusMessage)。 再次调用 RegisterModel 构造函数(并且 _companyDepartments 变为 null),但未触发 OnGetAsync,因此未填充 _companyDepartments。
据我所知,ViewData、ViewBag 和 TempData 在每个请求结束时都会被销毁 - 那么如何在请求之间保留一些数据?
【问题讨论】:
标签: c# asp.net-core razor-pages