Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow null value in required nullable DateTime in .NET MVC3 HTML form?

I have tried:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}", ConvertEmptyStringToNull = true)]
[Required(AllowEmptyStrings = true)]
public DateTime? BirthDateFrom { get; set; }

and

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
[Required]
public DateTime? BirthDateFrom { get; set; }

and all combinations with and without ConvertEmptyStringToNull and AllowEmptyStrings.

In view, I have:

@Html.EditorFor(m => m.BirthDateFrom)

I can submit form with valid date, but with empty string in that field, it just goes red and the form cannot be submitted. How to allow HTML form submission with null or empty string value in required nullable DateTime?

like image 345
Hogan Avatar asked Mar 13 '11 09:03

Hogan


People also ask

How do I assign a null value to a DateTime variable in C#?

The Nullable < T > structure is using a value type as a nullable type. By default DateTime is not nullable because it is a Value Type, using the nullable operator introduced in C# 2, you can achieve this. Using a question mark (?) after the type or using the generic style Nullable.

Does DateTime accept null?

DateTime CAN be compared to null; It cannot hold null value, thus the comparison will always be false. DateTime is a "Value Type". Basically a "value type" can't set to NULL. But by making them to "Nullable" type, We can set to null.

Should DateTime be nullable?

DateTime itself is a value type. It cannot be null.


1 Answers

It seems to me that simply removing the [Required] annotation entirely would meet your requirement.

like image 131
Mike Manard Avatar answered Sep 20 '22 13:09

Mike Manard