Daniel Santos Daniel Santos - 2 months ago 15
ASP.NET (C#) Question

ASP.NET MVC. Non required fields are required in validations

I do have a POCO Class with some non required fields:

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; }
}


but whenever I set the
[Required]
annotation or not. the validations fails.
I always got the "2nd interval is required" message on my view.

I'm using only Server validation.

How can I solve it?

Answer

The TimeSpan is not nullable by default

Use Nullable;

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

or

public TimeSpan? t2 { get; set; }