Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Html.TextBoxFor with input type=date? [duplicate]

I want to implement in my code. To that end, I have the following:

@Html.TextBoxFor(model => model.CreationDate, new { @type = "date" }) 

This code generates the following HTML:

<input data-val="true" data-val-date="The field CreationDate must be a date."               data-val-required="The CreationDate field is required."               id="CreationDate" name="CreationDate" type="date"               value="09/05/2012 15:02:19"> 

The value does not show up on the web page because type="date" expects data in YYYY-MM-DD format.

I've tried formatting the date, but that blows up, of course.

@Html.TextBoxFor(model => model.CreationDate.ToString("YYYY-MM-DD"),                   new { @type = "date" }) 

How do I use TextBoxFor method to properly display the construct? Or should I be using some other method (I already tried EditorFor but failed)?

CreationDate is of type DateTime.

like image 598
AngryHacker Avatar asked Aug 01 '14 18:08

AngryHacker


People also ask

How can set input type date in mm/dd/yyyy format using HTML?

To set and get the input type date in dd-mm-yyyy format we will use <input> type attribute. The <input> type attribute is used to define a date picker or control field. In this attribute, you can set the range from which day-month-year to which day-month-year date can be selected from.

Which HTML5 attributes can be used with HTML5 date input type to limit date selection?

The max attribute specifies the maximum value (date) for a date field. Tip: Use the max attribute together with the min attribute to create a range of legal values. Tip: To set or return the value of the min attribute, use the min property.


1 Answers

Try this;

@Html.TextBoxFor(model => model.CreationDate,            new { @type = "date", @Value = Model.CreationDate.ToString("yyyy-MM-dd") }) 

You have to handle null when setting the value.

OR

If you can change the Model you can try this;

[DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] public DateTime CreationDate{ get; set; } 

and in your view you can use EditorFor helper.

@Html.EditorFor(model => model.CreationDate, new { @type = "date" }) 
like image 76
Saranga Avatar answered Sep 25 '22 03:09

Saranga