让我们有一个模型
public class Model
{
public int Number { get; set; }
public DateTime Date { get; set; }
}
我观察到以下行为。Number属性的值为0,Date为1.1 0001 00:00:00,当未提交任何内容时,ModelState.IsValid的值为true。
DataAnnotationsModelValidatorProvider类和GetValidators方法具有以下代码片段
// Add an implied [Required] attribute for any non-nullable value type,
// unless they've configured us not to do that.
if (AddImplicitRequiredAttributeForValueTypes &&
metadata.IsRequired &&
!attributes.Any(a => a is RequiredAttribute)) {
attributes = attributes.Concat(new[] { new RequiredAttribute() });
}
如果我理解这一点,那么Number属性和DateTime属性应该设置为RequiredAttribute,验证例程应该将模型设置为无效并生成适当的错误消息。
所以我的问题是,为什么模型不是无效的?
我使用的是ASP.NET MVC 3
所以我的问题是,为什么模型不是无效的?
因为0
是一个完全有效的整数,而1.1 0001 00:00:00
是一个非常有效的DateTime。我不明白你为什么会认为你的模型是无效的。
使em可以为null,并使用Required属性进行装饰以达到所需效果:
public class Model
{
[Required]
public int? Number { get; set; }
[Required]
public DateTime? Date { get; set; }
}