2016-09-29 165 views
1

我有一個POCO類有一些非必填字段:ASP.NET MVC。非必填字段都需要驗證

class MyClass{ 

    [DataType(DataType.Time)] 
    [Display(Name = "1st interval")] 
    public TimeSpan t1{ get; set; } 

    [DataType(DataType.Time)] 
    [Display(Name = "2nd interval")] 
    public TimeSpan t2 { get; set; } 

    [DataType(DataType.Time)] 
    [Display(Name = "3rd interval")] 
    public TimeSpan t3 { get; set; } 
} 

但每當我設置[Required]註釋與否。驗證失敗。 我總是在我的觀點上得到「第二間隔是必需的」消息。

我使用只有服務器驗證。

我該如何解決?

+3

使屬性可爲空 - '公共時間跨度? t2 {get;組; }' –

+0

有兩種方法:使用可爲空的屬性或使用'[Bind(Exclude)]'。類似的問題:http://stackoverflow.com/questions/2142990/the-id-field-is-required-validation-message-on-create-id-not-set-to-required –

回答

1

TimeSpan是不是默認

使用可空可爲空;

public Nullable<TimeSpan> t2 { get; set; } 

public TimeSpan? t2 { get; set; } 
+0

它是否相當於公共TimeSpan? t2 {get; set;}? –