[英]Model binding using System.ComponentModel.DataAnnotations
[英]Validation Summary using System.ComponentModel.DataAnnotations;
我有一個帶有一些隨機屬性的ViewModel ...
public class TestViewModel
{
[Required]
[MaxLength(255)]
[Display(Name = "Test Name (1.B.1)")]
public string Name { get; set; }
[DataType("Date")]
[Display(Name = "Date Created")]
public DateTime DateCreated { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string ZIP { get; set; }
[Display(Name = "City")]
public int CityID { get; set; }
[Display(Name = "Country")]
public int CountryID { get; set; }
[Display(Name = "State")]
public int StateID { get; set; }
}
我沒有一次聲明CityID,StateID或CountryID是必需的值(不是),但是在我的ModelState.IsValid控制器中,它使檢查失敗,並且在ValidationMessageFor中,它需要使用City字段進行響應。
為什么會這樣呢? 什么時候地址1和地址2不拋出此類必需的通知?
這是表單字段之一:
<div class="form-group">
@Html.LabelFor(model => model.CountryID, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.CountryID, new { @class = "text-box single-line countries typeahead" })
@Html.ValidationMessageFor(model => model.CountryID)
</div>
</div>
CityID,CountryID和StateID是Required
因為它們是int
。
要使它們可選,請將它們設置為Nullable<int>
您可以刪除以下行為: source
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.