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.
The <input type="date"> defines a date picker. The resulting value includes the year, month, and day.
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.
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.
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.
I managed to do it by using the following code.
@Html.TextBoxFor(model => model.EndTime, new { type = "time" })
@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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With