Razor Pages On Server Validation returning for without some fields

Viewed 1993

I'm having an issue with a server side validation with Razor Pages (ASP.Net Core 2.0)

I have a page that creates a record

http://localhost:56876/Entries/Create?employeeID=112345

my code behind file for the OnGet looks like:

      [BindProperty]
        public EntryLog EntryLog { get; set; }
        public Employee Employee{ get; set; }
        public string empID { get; set; }

  public IActionResult OnGet(string employeeID)
        {
        empID = employeeID;
// for Selects for lookup tables
        ViewData["ReasonId"] = new SelectList(_context.Reason, "Id", "Name");
        ViewData["ReasonTypeId"] = new SelectList(_context.ReasonType, "Id", "Name");
            return Page();
        }

The code above works just fine and client validation works perfect but I have business logic validation that if the Entry Date is 90 between today's date and hired date that I should not let the entry to be saved.

    public async Task<IActionResult> OnPostAsync()
            {
    //Lookup current employeeID hiredDate. if is new employee do not continue.

                Employee  = await _context.Employee .FirstOrDefaultAsync(p => p.Id == EntryLog.EmployeeID);

//Server side validation
                var age = DateTime.Today.Day - Employee.HireDate.Day;
                if (age <= 90)
                {
                    ModelState.AddModelError("NewEmp", "Emp is New Warning");
                    return Page();
                }

                if (!ModelState.IsValid)
                {
                    return Page();
                }

                _context.EntryLog.Add(EntryLog);
                await _context.SaveChangesAsync();

                return RedirectToPage("./Index");
            }

My server side validation works but the problem is that when I return Page(); The form gets refreshed and the two selects elements get empty out and the EmployeeID element gets empty out as well.

My guess is that the return Page() on OnPostAsync() is not calling the OnGet() method.

How can I keep the page as it is without loosing the info?

2 Answers

You can simply call OnGet from your OnPost method, i.e.:

if (!ModelState.IsValid) {
    return OnGet();
}

This works for me in ASP.NET Core 2.2 and preserves all validation errors.

Related