Razor Pages On Server Validation returning for without some fields

落花浮王杯 提交于 2019-12-13 02:36:55

问题


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?


回答1:


You are right the return Page() does not call OnGet() method. I´ll try to explain what is happening:

Short Answer:

When you receive the Post request (OnPost()) and return Page() the server just returns the response (html), it does not make a new Get Request so that OnGet() get called again.

The two selects elements are being cleant because they are set up in OnGet() through ViewData (that is temporary) not in OnPost(). My suggestion is that you set the "selects" again on OnPost() (extract to a method to make it easier).

Long Answer:

When you access your Page (Entries/Create) by typing or being redirected through a link, the browser request the page to the server using HTTP METHOD GET, which will invoke OnGet method. Afterwards, when you send your form (considering method="POST") the request will be sent to the server and be caught by the OnPost method.

When you code return Page(), it is not sending back a response to browser saying "Hey, you have to make a GET request again (what would make OnGet be called again)", it is returning the end response (html) itself. That´s why OnGet() is not being called. What would make the OnGet() be called again would be return RedirectToPage("./Entities/Create"), but doing so you would lose your Model state (validation result).

The two selects elements are being cleant because they are set up in OnGet() through ViewData (that is temporary) not in OnPost(). My suggestion is that you set the "selects" again on OnPost() (extract to a method to make it easier).

Regards.




回答2:


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.



来源:https://stackoverflow.com/questions/45715684/razor-pages-on-server-validation-returning-for-without-some-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!