【问题标题】:Model validation not working with Razor Page & PageModel模型验证不适用于 Razor Page 和 PageModel
【发布时间】:2019-04-27 14:10:09
【问题描述】:

我有一个 Razor 页面,它有一个标签可以打印出错误消息,并且还打印了 ModelState.IsValid 的值。

@page
@model IndexModel

<form asp-page="Index" method="get">
    <input asp-for="Message"/>
    <span asp-validation-for="Message"></span>
    <input type="submit" value="Submit"/>
</form>

<p>ModelState.IsValid = @Model.ModelIsValid</p>

PageModel 带有正则表达式要求注释:

public class IndexModel : PageModel
{
    [FromQuery]
    [RegularExpression("^[A-Za-z]*$")]
    public string Message { get; set; }

    public bool ModelIsValid { get; private set; }

    public void OnGet()
    {
        ModelIsValid = ModelState.IsValid;
    }
}

尽管我将 Message 设置为什么或根本不添加它,该模型始终有效。

NB Message 已正确填充。

注意 2 添加 [Required(AllowEmptyStrings = false)] 或将 [FromQuery] 替换为 [BindProperty(SupportsGet = true)] 都不会改变行为。

为什么我的注释没有生效?

我在这里分享了完整的项目:https://1drv.ms/u/s!Au6otEu-6FtC2VFoLNCTDydGUSIR

【问题讨论】:

  • 我在 .NET Core 2.1 中重现了您的问题,发现 ModelState.IsValid 在第一次加载时返回 true,但在提交非字母时,例如12345 甚至是乱码,例如$&amp;%*^@ 页面响应此消息:The field Message must match the regular expression '^[A-Za-z]*$'ModelState.IsValid 返回 false。你读过this issue 了吗?
  • 谢谢@TetsuyaYamamoto。这正是问题所在!我将.SetCompatibilityVersion(CompatibilityVersion.Version_2_1); 添加到StartUp,现在一切正常。您想将其添加为答案吗?

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


【解决方案1】:

解决方法是改变

services.AddMvc();

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

Startup.cs

根据https://github.com/aspnet/Mvc/issues/6790,这将允许您的应用程序启用此行为。

【讨论】:

    猜你喜欢
    • 2019-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多