为什么 ModelState.IsValid 在没有 [Required] 的情况下检查模型属性?

问题描述 投票:0回答:1

我是 ASP.NET 新手。在 ASP.NET Core (6.0) Razor Pages 项目中,我发现一个问题,

ModelState.IsValid
会检查模型的所有属性。例如,我有一个模型:

public class SimpleModel
    {
        
        public int Id { get; set; }
        [Required]
        public string Name { get; set; }

        public int Age { get; set; }
    }

和一页

Example.cshtml
,其形式为:

@page "/example"
@model StudentManagement.Pages.ExampleModel
@{
    ViewData["Title"] = "Example";
}

<form method="post" class="mt-3">
    <input hidden asp-for="simpleModel.Id" />

    <div class="form-group row">
        <label asp-for="simpleModel.Name" class="col-sm-2 col-form-label">
        </label>
        <div class="col-sm-10">
            <input asp-for="simpleModel.Name" class="form-control" placeholder="Name">
            <span asp-validation-for="simpleModel.Name"></span>
        </div>
    </div>
    <div class="form-group row">
        <label asp-for="simpleModel.Age" class="col-sm-2 col-form-label"></label>
        <div class="col-sm-10">
            <input asp-for="simpleModel.Age" class="form-control" placeholder="Age">
        </div>
    </div>

    <div class="form-group row">
        <div class="col-sm-10">
            <button type="submit" class="btn btn-primary">Update</button>
        </div>
    </div>
</form>

Example.cshtml.cs

public class ExampleModel : PageModel
    {
        public SimpleModel simpleModel { get; set; }
        public ExampleModel()
        {
            simpleModel = new SimpleModel()
            {
                Id = 1,
                Name = "Tom",
                Age = 15
            };
        }
        public void OnGet()
        {
        }

        public IActionResult OnPost(SimpleModel simpleModel)
        {
            if (ModelState.IsValid)
            {
                this.simpleModel.Age = simpleModel.Age;
                this.simpleModel.Name = simpleModel.Name;
            }
            return Page();
        }
    }

问题是当点击带有空白

Update
Age
时,
ModelState.IsValid
为假。为什么
ModelSate
不忽略
Age
,即使它没有[必填]?

我尝试使用

int? Age
ModelState.IsValid
返回 true,我仍然想知道它是如何工作的。

c# asp.net-core razor-pages
1个回答
2
投票

ModelState.IsValid
指示是否可以将请求中的传入值正确绑定到模型,以及在模型绑定过程中是否破坏了任何显式指定的验证规则。

官方关于

non-nullable properties or parameters
的解释如下

验证系统处理不可为空的参数或绑定的参数 属性就好像它们有

[Required(AllowEmptyStrings = true)]
属性。通过启用 Nullable 上下文,MVC 隐式启动 验证不可为 null 的属性或参数,就像它们已被验证一样 归因于
[Required(AllowEmptyStrings = true)]
属性。

如果应用程序是使用

<Nullable>enable</Nullable>
构建的,则缺少 JSON 或表单帖子中的名称值会导致验证错误。 使用可为空的引用类型允许空值或缺失值 为 Name 属性指定:

您可以参考这个链接了解更多

Model validation

© www.soinside.com 2019 - 2024. All rights reserved.