【问题标题】:Repopulate form data when validation fails in aspnet core Razor Page在 aspnet core Razor 页面中验证失败时重新填充表单数据
【发布时间】:2018-09-27 12:11:32
【问题描述】:

提前感谢您的帮助

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

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

需要帮助...

【问题讨论】:

    标签: c# asp.net-core razor-pages


    【解决方案1】:

    如果您这样做,则会自动重新填充表单值

    1. 在相关的 PageModel 属性上使用 [BindProperty] 属性,
    2. 使用 input tag helpers 中的 asp-for 属性在 UI(Razor 内容页面)中建立双向绑定
    3. 如果遇到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");
        }
    }
    

    【讨论】:

    • 感谢迈克的回复。好吧,我知道这可以工作,但是当您使用下拉(选择)绑定属性时它不起作用。例如,如果我绑定一个下拉列表并在表单上选择其值到“ABC”并回发,并且如果模型状态失败,我无法重新绑定该选择列表并将 ABC 作为表单上的选定值
    • 迈克·布林德,我整理了这个。感谢您的帮助
    • 你是怎么排序的?
    猜你喜欢
    • 1970-01-01
    • 2010-12-30
    • 1970-01-01
    • 1970-01-01
    • 2013-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-23
    相关资源
    最近更新 更多