在 aspnet core Razor 页面中验证失败时重新填充表单数据

Kam*_*mal 5 c# asp.net-core razor-pages

预先感谢您的任何帮助

我正在 aspnet core 2.1 razor 页面工作。当验证失败或 ModelState 无效时,我需要重新填充表单数据。在MVC中,我们可以使用return View(model)但是如何在aspnet core 2.1 razor页面中做到这一点。

我尝试过return Page(),但这会触发服务器端验证,但不会重新填充表单中的数据

需要帮忙...

Mik*_*ind 7

如果您执行以下操作,则会自动重新填充表单值

  1. 使用[BindProperty]相关 PageModel 属性上的属性,
  2. 使用输入标记帮助asp-for程序中的属性在 UI(Razor 内容页面)中建立双向绑定
  3. return Page()如果发生这种情况请致电ModelState.IsValid == false

以下是证明这一点所需的最少步骤:

表单:

<form method="post">
<input asp-for="FirstName"/><span asp-validation-for="FirstName"></span><br />
    <input type="submit" />
</form>
Run Code Online (Sandbox Code Playgroud)

和一个页面模型:

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

    public IActionResult OnPost()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }
        return RedirectToPage("index");
    }
}
Run Code Online (Sandbox Code Playgroud)