0

I have DateTime Property in my Model class ,

Then in view I am using :

 @Html.TextBoxFor(m => m.BirthDay, new {@disabled="true" , @value="" })

In my View TextBox Displayed as [01/01/0001 00:00:00] , how to force it be Empty ?

StringBuilder
  • 1,619
  • 4
  • 32
  • 52
  • http://stackoverflow.com/questions/3734829/datetime-field-and-html-textboxfor-helper-how-to-use-it-correctly dup – indiPy Nov 20 '12 at 09:51

3 Answers3

4

The default value of a DateTime = 01/01/0001 00:00:00

This is because a DateTime is a struct and not an object. This also counts for some other C# varables like Int where the default value = 0

Other C# variables like String are nullable by default because they are an object.

To make these structs nullable you need to add a QuestionMark to the variable declaration like

public DateTime? BirthDay { get; set; }

Now your DateTime can contain null values. And the value of your textbox will contain nothing for default


Adding the ? to a struct is C# sugar for Nullable<T> where T is a struct.
So DateTime? can be rewritten as Nullable<DateTime>.

SynerCoder
  • 12,493
  • 4
  • 47
  • 78
middelpat
  • 2,555
  • 1
  • 20
  • 29
1

Can this work? Change in model:

public DateTime? BirthDay {get; set;}

instead of

public DateTime BirthDay {get; set;}
middelpat
  • 2,555
  • 1
  • 20
  • 29
nils
  • 558
  • 5
  • 13
  • Try to explain why this works so this solution won't just work for this problem but he also will have the knowledge for the future – middelpat Nov 20 '12 at 10:54
0

this will do it.

@Html.TextBox("BirthDay", "", new {@disabled="true" })

It doesn't strongly type the TextBox so you can set any value you want, binding in the other direction will work as normal,

Html.Textbox VS Html.TextboxFor

Community
  • 1
  • 1
Liam
  • 27,717
  • 28
  • 128
  • 190