0

I have a legacy MVC application, which has an input date field;

@Html.EditorFor(model => model.CompleteBy)

which is decorated in the ViewModel as

[Display(Name = "Complete By")]
[DataType(DataType.Date)]
public Nullable<DateTime> CompleteBy { get; set; }

I have an EditorTemplate for date fields;

@model DateTime?  
 @Html.TextBox("", (Model.HasValue ? Model.Value.ToLongDateString() : string.Empty), 
    new { @class = "datePicker", @style = "width:200px;" })

And in my Javascript file I assign a datepicker to the datepicker class as follows;

var constantDateFormat = "dd MM yy";

$("input[type=date]").datepicker({
    showOn: "both",
    dateFormat: constantDateFormat,
    changeMonth: true,
    changeYear: true
});

When this application is accessed in Edge, the date no longer appears, instead I see mm/dd/yyyy. And the datepicker is completely different to before.

So how do I fix this for Edge?

arame3333
  • 9,887
  • 26
  • 122
  • 205
  • That suggests you `EditorTemplate` is not being called and the default `EditorTempate` is being used (which generates `` because of the `[DataType]` attribute (which in turn generates the browsers HTML-5 date picker which required the format to be `yyyy-MM-dd` (refer [this answer](https://stackoverflow.com/questions/43820926/specify-date-format-in-mvc5-dd-mm-yyyy/43826746#43826746) for more detail) –  Jan 26 '18 at 22:01
  • And the fact that your jquery selector is `$("input[type=date]")` and your `EditorTemplate` does not generate the `type="date"` attribute confirms your `EditorTemplate` is not being called (and your script would never execute) –  Jan 26 '18 at 22:03

2 Answers2

0

Try removing the [DataType(DataType.Date)] from the data annotation, or you can try using the type as text as below

@Html.TextBox("", (Model.HasValue ? Model.Value.ToLongDateString() : string.Empty), new {@type = "text", @class = "datePicker", @style = "width:200px;" })
gvk
  • 597
  • 7
  • 27
0

The answer from gvk put me on the right track. Unfortunately the nice EditorTemplate that always worked before for dates no longer does, and I found trying to change the type from "date" to "text" does not work either. So what I did was change the EditorFor to TextBoxFor;

@Html.TextBoxFor(model => model.CompleteBy, "{0:d MMMM yyyy}", new { @class = "datepicker" })

Note I had to include the date format as well. Setting the DateFormat attribute for the field did not appear to work.

Then in JQuery I had

$("input.datepicker:text").datepicker({
    showOn: "both",
    dateFormat: constantDateFormat,
    changeMonth: true,
    changeYear: true
});

So before migrating to Windows 10 and Edge, I need to change the date code on all of the applications we use.

arame3333
  • 9,887
  • 26
  • 122
  • 205