35

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 5

54

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.

Sign up to request clarification or add additional context in comments.

7 Comments

+1 Actually, it seems that with these data annotations on the property, Html.EditorForm(m => m.LastStartDate) renders an <input type=date>. Thus, no need to override the type attribute.
@JørnSchou-Rode Thanks. Shouldn't that be Html.EditorFor?
@JørnSchou-Rode I've updated my answer in response to your comment.
Indeed it should. The m is a typo :)
Where does EditorFor come from?
|
35

I managed to do it by using the following code.

@Html.TextBoxFor(model => model.EndTime, new { type = "time" }) 

3 Comments

Just a late comment why this answer shows only time in Chrome?
Input type date isn't supported in Safari or IE. Were you using either of those? Source: caniuse.com/#search=date
Html.EditorFor should be used instead textboxfor
2
 @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() 

Comments

1

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> 

}

Comments

-3

You will get it by tag type="date"...then it will render beautiful calendar and all...

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.