I write application in ASP .NET MVC 5.1
I have a field:
[DisplayName("Date of Birth")]
[DataType(DataType.Date)]
public DateTime BirthDate { get; set; }
and then in View
<div class="form-group">
@Html.LabelFor(model => model.BirthDate, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.BirthDate, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.BirthDate, "", new { @class = "text-danger" })
</div>
</div>
which translates to:
if I just change annotiations above property in model to:
[DisplayName("Date of Birth")]
[DataType(DataType.DateTime)]
I don't get any picker displayed. If I change them to:
[DisplayName("Date of Birth")]
[DataType(DataType.Time)]
there is only hh:mm to choose from.
Question: Displaying DateTime picker instead of Date picker in ASP .NET MVC 5.1. I am asking for ASP .NET 5.1 HTML 5 specific solution.
My Solution was slightly different. Although it does use javascript/jQuery to accomplish. I went with the Fact if you use the data annotation
Now you have to have jqueryUI scripts and CSS included on the page(or in a bundle). In Javascript :
Since the
DataType(DataType.DateTime)
makes a input with the type being datetime. Just use that fact and take all of those and make them date time pickers using jQuery. I have this code that is included in my_Layout
page bundle.So now all I have to do is annotate the property in the model and It will show up as a jQuery Date time picker. You may want to change the defaults for the date time picker. Hope this helps someone out.
You are getting this date picker because of html5 and browser supporting html5. Possible options :
Your requirements are pretty picky...
Specifying the attribute
Datatype
for a field, will generate aninput
having astype
the attribute specified. That's why when you add[DataType(DataType.Date)]
, the input generated will be a date picker, but if you add[DataType(DataType.DateTime)]
, the input will be of typedatetime
, thus why you don't get any picker displayed. Why? Because a few years ago, the browsers supporting inputdatetime
decided to stop supporting it and W3C removed this feature due to lack of implementation.However, not so long ago, some browser vendors started supporting again
datetime-local
which is back on the draft. As of now, the latest versions ofChrome
,Opera
andMicrosoft Edge
support it.One solution would be to use the BootStrap or the jQuery Datetime Picker as Ajay Kumar suggested.
Another one would be, if you don't mind the few supporting browsers, to use
datetime-local
. Like this for instance:Add in object definition:
in .cshtml add as: