在 aspnet core Razor Page 中验证失败时重新填充表单数据
Repopulate form data when validation fails in aspnet core Razor Page
提前感谢您的帮助
我正在使用 aspnet core 2.1 razor 页面。当验证失败或 ModelState 无效时,我需要重新填充表单数据。
在 MVC 中,我们可以使用 return View(model)
但如何在 aspnet core 2.1 razor 页面中使用。
我尝试了 return Page()
,但这会触发服务器端验证但不会重新填充表单中的数据
需要帮助...
如果您
会自动重新填充表单值
- 在相关的 PageModel 属性上使用
[BindProperty]
属性,
- 使用 input tag helpers 中的
asp-for
属性在 UI(Razor 内容页面) 中建立双向绑定
- 在
ModelState.IsValid == false
的情况下调用 return Page()
。
以下是演示此操作所需的最少步骤:
一个表格:
<form method="post">
<input asp-for="FirstName"/><span asp-validation-for="FirstName"></span><br />
<input type="submit" />
</form>
还有一个 PageModel:
public class FormValidationModel : PageModel
{
[BindProperty, StringLength(5)]
public string FirstName { get; set; }
public IActionResult OnPost()
{
if (!ModelState.IsValid)
{
return Page();
}
return RedirectToPage("index");
}
}
提前感谢您的帮助
我正在使用 aspnet core 2.1 razor 页面。当验证失败或 ModelState 无效时,我需要重新填充表单数据。
在 MVC 中,我们可以使用 return View(model)
但如何在 aspnet core 2.1 razor 页面中使用。
我尝试了 return Page()
,但这会触发服务器端验证但不会重新填充表单中的数据
需要帮助...
如果您
会自动重新填充表单值- 在相关的 PageModel 属性上使用
[BindProperty]
属性, - 使用 input tag helpers 中的
asp-for
属性在 UI(Razor 内容页面) 中建立双向绑定
- 在
ModelState.IsValid == false
的情况下调用return Page()
。
以下是演示此操作所需的最少步骤:
一个表格:
<form method="post">
<input asp-for="FirstName"/><span asp-validation-for="FirstName"></span><br />
<input type="submit" />
</form>
还有一个 PageModel:
public class FormValidationModel : PageModel
{
[BindProperty, StringLength(5)]
public string FirstName { get; set; }
public IActionResult OnPost()
{
if (!ModelState.IsValid)
{
return Page();
}
return RedirectToPage("index");
}
}