Warm tip: This article is reproduced from stackoverflow.com, please click
asp.net-core c# razor-pages

Repopulate form data when validation fails in aspnet core Razor Page

发布于 2020-03-27 15:41:28

Thanks in advance for any help

I am working in aspnet core 2.1 razor pages. I need to repopulate form data when validation fails or ModelState is Invalid. In MVC, we can use return View(model) but how to do that in aspnet core 2.1 razor page.

I tried return Page(), but that fires server side validation but does not repopulate data in form

Need Help...

Questioner
Kamran Ajmal
Viewed
90
Mike Brind 2018-09-27 22:17

Repopulation of the form values occurs automatically if you

  1. Use the [BindProperty] attribute on the relevant PageModel properties,
  2. Use the asp-for attribute in your input tag helpers to establish two-way binding in the UI (Razor content page)
  3. Call return Page() in the event that ModelState.IsValid == false.

Here are the minimal steps required to demonstrate this:

A form:

<form method="post">
<input asp-for="FirstName"/><span asp-validation-for="FirstName"></span><br />
    <input type="submit" />
</form>

And a PageModel:

public class FormValidationModel : PageModel
{
    [BindProperty, StringLength(5)]
    public string FirstName { get; set; }

    public IActionResult OnPost()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }
        return RedirectToPage("index");
    }
}