[英]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.