我有一个带有一些随机属性的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字段。
为什么会这么想?当Address1和Address2没有抛出这些必要的通知时?
这就是其中一个表单字段:
<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>
答案 0 :(得分:0)
CityID,CountryID和StateID为Required
,因为它们是int
。
要使它们成为可选项,请将它们设为Nullable<int>
您可以删除以下行为:source
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;