0
@if (Model.RecDateFrom.HasValue)
{
    @Html.EditorFor(model => model.RecDateFrom, 
        new {htmlAttributes = 
            new {@Value = Model.RecDateFrom.Value.ToString("yyyy-MM-dd"), 
                 @class = "form-control input-sm small-input-fix"}})
}
else
{
    @Html.EditorFor(model => model.RecDateFrom, 
        new {htmlAttributes = new {@class = "form-control input-sm small-input-fix"}})
}

@Html.ValidationMessageFor(model => model.RecDateFrom, "", new {@class = "text-danger"})

You can see above how I have to handle if the datetime is null before setting the value. I have to set the value because MVC uses the incorrect format for a date input, making it so chrome doesn't have the correct default value.

I do not want to use the accepted solution in this question because that changes the format of the display for also.

I've tried using editor templates, but it seems like you have to start from scratch, rather than extending the built in editor template for Date datatypes (this seems like a large flaw of MVC, unless I'm missing something).

Community
  • 1
  • 1
Dave
  • 1,645
  • 2
  • 23
  • 39

1 Answers1

2

If you are wanting to render the browsers HTML5 datepicker, you just need to apply the correct attributes to you property. Note the format string must be in the ISO format.

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime RecDateFrom { get; set; }

and then in the view

@Html.EditorFor(m => m.RecDateFrom, new { htmlAttributes = new { @class = "form-control input-sm small-input-fix" } })

Side note: The HTML5 datepicker is not supported in older browsers and not yet at all in FireFox, so it may be better (at least in the short term) to use a jquery plugin (and set the format in the plugin initializer). For example, using the jquery ui datepicker - $('#datepicker').datepicker({ dateFormat: 'dd-mm-yy' })

  • By doing this, When I use `Html.DisplayFor` on a Date it will print out as yyyy-MM-dd, which I don't want. Perhaps I should make a EditFormat attribute? – Dave Mar 18 '15 at 16:07
  • No, as always you should be using view models to represent what you want to display/edit. Perhaps not always necessary for a simple display page, but you should always use one for an edit view (and then you can apply different attributes for the edit view model vs the display model) –  Mar 18 '15 at 23:57
  • The DisplayFormat attribute property should be ApplyFormatInEditMode instead of ApplyInEditMode. – John81 Dec 16 '16 at 16:29
  • @John81, Thanks :) –  Dec 16 '16 at 20:30