![](/img/trans.png)
[英]Why does ModelState report errors when I update the model before the ModelState.IsValid check?
[英]Why does ModelState.IsValid check the model properties without [Required]?
我刚接触ASP,在一个ASP.NET Core (6.0) razorpage项目中,我发现一个问题, ModelState.IsValid
会检查model的所有属性。比如我有一个model:
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
with a blank Age
时, ModelState.IsValid
为 false。 为什么ModelSate
即使没有 [Required] 也不会忽略Age
?
我试过使用int? Age
int? Age
和ModelState.IsValid
返回 true,我仍然想知道它是如何工作的。 提前致谢。
ModelState.IsValid
指示是否可以将来自请求的传入值正确绑定到 model,以及在 model 绑定过程中是否违反了任何明确指定的验证规则。
官方关于non-nullable properties or parameters
的解释如下
验证系统将不可为 null 的参数或绑定属性视为具有
[Required(AllowEmptyStrings = true)]
属性。 通过启用可为空的上下文,MVC 隐式地开始验证不可为空的属性或参数,就好像它们已被赋予[Required(AllowEmptyStrings = true)]
属性一样。如果应用程序是使用
<Nullable>enable</Nullable>
构建的,则 JSON 或表单发布中的名称缺失值会导致验证错误。 使用可为 null 的引用类型以允许为 Name 属性指定 null 或缺失值:
您可以参考此链接以了解有关Model validation
的更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.