我的 ViewModel 看起來像這樣:
public class BookingViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public DateTime CheckInDate { get; set; }
public DateTime CheckOutDate { get; set; }
//Need this to display which room was chosen by the user
public RoomTypeDTO? RoomType { get; set; }
public int RoomTypeId { get; set; }
}
該視圖(部分)如下所示:
<div>
<label asp-for="FirstName"></label>
<input asp-for="FirstName" class="col-xs-4"/>
<span asp-validation-for="FirstName" class="text-danger"></span>
</div>
<br />
<div>
<label asp-for="LastName"></label>
<input asp-for="LastName" class="col-xs-4" />
<span asp-validation-for="LastName" class="text-danger"></span>
</div>
<div>.......
當 ViewModel 從此視圖發送到控制器操作 Create 時,如果我沒有在 FirstName 和 LastName 文本框中輸入任何內容,我會得到無效的模型狀態,然后出現默認錯誤“First Name is required”
這怎么可能發生?這與我的流利驗證相沖突。
uj5u.com熱心網友回復:
默認情況下,不可為空的型別被視為用[Required]屬性修飾過的型別。
從 docs Non-nullable reference types 和 [Required] 屬性:
驗證系統將不可為空的引數或系結屬性視為具有 [Required(AllowEmptyStrings = true)] 屬性。通過啟用 Nullable 背景關系,MVC 隱式開始驗證非泛型型別或引數上的不可為空屬性,就好像它們已被賦予 [Required(AllowEmptyStrings = true)] 屬性一樣。考慮以下代碼:
public class Person
{
public string Name { get; set; }
}
如果應用程式是使用啟用構建的,則 JSON 或表單帖子中名稱的缺失值會導致驗證錯誤。使用可為空的參考型別以允許為 Name 屬性指定空值或缺失值:
public class Person
{
public string? Name { get; set; }
}
可以通過在 Program.cs 中配置SuppressImplicitRequiredAttributeForNonNullableReferenceTypes來禁用此行為 :
builder.Services.AddControllers(
options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/508214.html
標籤:C# asp.net-mvc
上一篇:正則運算式
