I am working an asp.net mvc in visual studio 2013 and one of the fields is a date input but when clicking in the field and having focus in the field the automatic HTML5 datepicker does not come up. If I put the field in manually it comes up but then it doesn't map to that particular field. In the data annotations I have included [DataType(DataType.Date)] but this doesn't bring up the HTML5 date picker. How do I achieve this in asp.net below is the code for the field in particular
<div class="form-group">
@Html.LabelFor(model => model.CustomerJoinDate, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.CustomerJoinDate, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.CustomerJoinDate, "", new { @class = "text-danger" })
</div>
</div>
Can't remember exactly when this was added but in older versions of ASP.NET MVC you could either modify the default editor template to add support for it or use TextBoxFor
which allows you to specify any custom attributes:
@Html.TextBoxFor(model => model.CustomerJoinDate, new {
@class = "form-control",
type = "date"
})
If you want your DateTime model properties to use the same template without having to repeat the same Razor code over and over, define a partial view called DateTime.cshtml
(or DateTime.vbhtml
) in your Shared/EditorTemplates
folder, with content similar to:
@model DateTime
@Html.TextBoxFor(
m => m,
"{0:MM/dd/yyyy}",
new { @class = "form-control date", type = "date" })
Then replace your Razor bindings with:
@Html.EditorFor(model => model.CustomerJoinDate)
and so on, for each date field which should use this template.
This uses an overload of TextBoxFor that allows you to specify a format string for the input, which is helpful for "masking" the time portion of the DateTime value (assuming you only want to enter a date).
Since not every browser supports a native datepicker, you could use the date
class in this example to apply a polyfill as necessary (or simply use type=date
as your selector).
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