Reputation: 3373
I have ASP .NET Сore Razor Page where I am populating select html list with company departments (Names are displayed while Ids goes to values). Specific сompany, it's Id and departments are determined by input parameter in Get request (the following example is greatly simplified):
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();
}
On Post I perform a check and if it fails - I need to get department Name from department Id, but _companyDepartments is already empty here. RegisterModel constructor is called and _companyDepartments becomes null but OnGetAsync is NOT fired afterwards and therefore _companyDepartments is NOT filled.
If check is passed I need to add user to database but _companyId is also already null there.
After that I reload the same page (with some additional StatusMessage on the top of it). And again RegisterModel constructor is called (and _companyDepartments becomes null) but OnGetAsync is NOT fired and therefore _companyDepartments is NOT filled.
As far As I know ViewData, ViewBag, and TempData are destroyed at the end of each request - so how can I persisting some data between requests?
Upvotes: 1
Views: 1179
Reputation: 8459
You can set the Dictionary as a static variable.
public static Dictionary<long, string> _companyDepartments;
Upvotes: 1