Date does not display from Model on HTML input type date
I am trying to display a date type input on my create and edit Razor Views... The date picker works fine but when editing I do get the value from the Model but the date picker does not display it...
View
<div class="form-group form-md-line-input">
@Html.TextBoxFor(model => model.InitialDate, new { @class = "form-control", type = "date" })
@Html.ValidationMessageFor(model => model.InitialDate)
@Html.LabelFor(model => model.InitialDate)
</div>
Model
public Nullable<System.DateTime> InitialDate { get; set; }
I have tried using the DataAnnotations
but the same thing happens the date picker only allows me to select the date on the create but when editing it does not display the date from the model although when I looked at the HTML Code that is rendered, the value for the date is being set but the control does not display it.
HTML View
<input class="form-control" data-val="true" data-val-date="The field InitialDate must be a date." id="InitialDate" name="InitialDate" type="date" value="3/3/2015 12:00:00 AM">
I also removed the time from attribute value from the browser's developers tools to see if it works, but it didn't work either...
<input class="form-control" data-val="true" data-val-date="The field InitialDate must be a date." id="InitialDate" name="InitialDate" type="date" value="3/3/2015">
How can I Display the Date from the Model in the date picker? Any help will be appreciated...
Solution 1:
If your using this to generate the browsers HTML5 datepicker implementation, the format of the date needs to be yyyy-MM-dd
(ISO format). Using TextBoxFor()
it needs to be
@Html.TextBoxFor(m => m.InitialDate, "{0:yyyy-MM-dd}", new { @class = "form-control", type = "date" })
Alternatively, add the following attributes to the property
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> InitialDate { get; set; }
and in the view use
@Html.EditorFor(m => m.InitialDate)
Note this adds the type="date"
attribute