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.
5 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.
7 Comments
Html.EditorForm(m => m.LastStartDate) renders an <input type=date>. Thus, no need to override the type attribute.m is a typo :)I managed to do it by using the following code.
@Html.TextBoxFor(model => model.EndTime, new { type = "time" })
3 Comments
If you want to use @Html.EditorFor() you have to use jQuery ui and update your Asp.net Mvc to 5.2.6.0 with NuGet Package Manager.
@Html.EditorFor(m => m.EntryDate, new { htmlAttributes = new { @class = "datepicker" } })
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script>
$(document).ready(function(){
$('.datepicker').datepicker();
});
</script>
}