Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 4 Razor adding input type date

I'm wondering how to insert a <input type="date"/> for datetime attributes of my model. As for now Razor creates a plain input element with type="datetime". I want to make use of the new input types of HTML5.

like image 318
Geethanga Avatar asked Jan 20 '13 11:01

Geethanga


People also ask

How do you input a date into type?

The <input type="date"> defines a date picker. The resulting value includes the year, month, and day.

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.

Is input type date accessible?

Custom JavaScript Datepicker controls are almost always inaccessible to keyboard and screen reader users. HTML5 input type="date" will give you an accessible date picker in most browsers, but not all like Safari macOS where native datepickers are not supported yet.


3 Answers

The input date value format needs the date specified as per https://www.rfc-editor.org/rfc/rfc3339#section-5.6 full-date.

So I've ended up doing:

<input type="date" id="last-start-date" value="@string.Format("{0:yyyy-MM-dd}", Model.LastStartDate)" />

I did try doing it "properly" using:

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

with

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

Unfortunately that always seemed to set the value attribute of the input to a standard date time so I've ended up applying the formatting directly as above.

Edit:

According to Jorn if you use

@Html.EditorFor(model => model.LastStartDate)

instead of TextBoxFor it all works fine.

like image 163
Giles Roberts Avatar answered Oct 02 '22 19:10

Giles Roberts


I managed to do it by using the following code.

@Html.TextBoxFor(model => model.EndTime, new { type = "time" })
like image 30
Geethanga Avatar answered Oct 01 '22 19:10

Geethanga


 @Html.TextBoxFor(m => m.EntryDate, new{ type = "date" })

 or type = "time"

 it will display a calendar
 it will not work if you give @Html.EditorFor()
like image 42
Md Shahriar Avatar answered Oct 02 '22 19:10

Md Shahriar