MVC4 DataType.Date EditorFor won't display date value in Chrome, fine in Internet Explorer

180,230

Solution 1

When you decorate a model property with [DataType(DataType.Date)] the default template in ASP.NET MVC 4 generates an input field of type="date":

<input class="text-box single-line" 
       data-val="true" 
       data-val-date="The field EstPurchaseDate must be a date."
       id="EstPurchaseDate" 
       name="EstPurchaseDate" 
       type="date" value="9/28/2012" />

Browsers that support HTML5 such Google Chrome render this input field with a date picker.

In order to correctly display the date, the value must be formatted as 2012-09-28. Quote from the specification:

value: A valid full-date as defined in [RFC 3339], with the additional qualification that the year component is four or more digits representing a number greater than 0.

You could enforce this format using the DisplayFormat attribute:

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

Solution 2

In MVC5.2, add Date.cshtml to folder ~/Views/Shared/EditorTemplates:

@model DateTime?
@{
    IDictionary<string, object> htmlAttributes;
    object objAttributes;
    if (ViewData.TryGetValue("htmlAttributes", out objAttributes))
    {
        htmlAttributes = objAttributes as IDictionary<string, object> ?? HtmlHelper.AnonymousObjectToHtmlAttributes(objAttributes);
    }
    else
    {
        htmlAttributes = new RouteValueDictionary();
    }
    htmlAttributes.Add("type", "date");
    String format = (Request.UserAgent != null && Request.UserAgent.Contains("Chrome")) ? "{0:yyyy-MM-dd}" : "{0:d}";
    @Html.TextBox("", Model, format, htmlAttributes)
}

Solution 3

As an addition to Darin Dimitrov's answer:

If you only want this particular line to use a certain (different from standard) format, you can use in MVC5:

@Html.EditorFor(model => model.Property, new {htmlAttributes = new {@Value = @Model.Property.ToString("yyyy-MM-dd"), @class = "customclass" } })

Solution 4

In MVC 3 I had to add:

using System.ComponentModel.DataAnnotations;

among usings when adding properties:

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]

Especially if you are adding these properties in .edmx file like me. I found that by default .edmx files don't have this using so adding only propeties is not enough.

Solution 5

If you remove [DataType(DataType.Date)] from your model, the input field in Chrome is rendered as type="datetime" and won't show the datepicker either.

Share:
180,230

Related videos on Youtube

Ben Finkel
Author by

Ben Finkel

Updated on April 27, 2020

Comments

  • Ben Finkel
    Ben Finkel about 4 years

    I'm using the DataType.Date attribute on my model and an EditorFor in my view. This is working fine in Internet Explorer 8 and Internet Explorer 9, but in Google Chrome it is showing a date picker and instead of displaying the value it just displays "Month/Day/Year" in faded gray text.

    Why won't Google Chrome display the value?

    Model:

    [DataType(DataType.Date)]
    public Nullable<System.DateTime> EstPurchaseDate { get; set; }
    

    View:

    <td class="fieldLabel">Est. Pur. Date</td>
    <td class="field">@Html.EditorFor(m=>m.EstPurchaseDate)</td>
    

    Chrome

    Internet Explorer

  • Ben Finkel
    Ben Finkel over 11 years
    Darin thank you, that was perfect! You've answered so many of my MVC questions over the past two years, you rock!
  • Ben Finkel
    Ben Finkel over 11 years
    Thanks Bernie. I wasn't so trouble with the picker showing up as I was with the data not being put into the input box. This is good to know though.
  • cleftheris
    cleftheris over 11 years
    Opera renders a datepicker though. Use modernizr to do some polyfill
  • Coops
    Coops almost 11 years
    Great answer but I feel this is appealing you have to force it just to get the control to work properly!
  • Marjan Venema
    Marjan Venema almost 11 years
    What would be the way of doing this "globally" for all properties marked [DataType(DataType.Date)] so I wouldn't have to mark all these properties separately with the risk of missing some?
  • Piotr Kula
    Piotr Kula about 10 years
    Darin, What can us people outside USA do? How can I set the specification value but display a custom date format? ie, UK?
  • David
    David about 10 years
    If you do it this way, Chrome won't give you a date picker. I'm using your solution, but modifying so that 1) I DO use the DisplayFormat attribute 2) Change the test to check if the browser type is chrome, then do @Html.EditorFor(m=>m.EstPurchaseDate) 3) Else do @Html.TextBox("EstPurchaseDate", dt.ToString("MM/dd/yyyy")) Note: on #2, a better check would be if the browser understands HTML5, but I don't know how to do that.
  • Chris Pratt
    Chris Pratt almost 10 years
    @ppumkin: This is not US specific. In fact, the reason the HTML5 specification uses YYYY-MM-DD is because it's an international standard (ISO 8601). If you need to display the date in a different format, you'll need to utilize view models in your views so that you can set the date format for your form to ISO 8601, but set the date format for something like a detail view to whatever the localized version you desire is.
  • Chris Pratt
    Chris Pratt almost 10 years
    If it's supposed to be a date, it should be rendered as an input of type date. Using datetime as a work-around is inappropriate, since it doesn't semantically represent the data.
  • Piotr Kula
    Piotr Kula almost 10 years
    The format displayed in Chrome is whatever is set in your systems globalization settings. So, yes, set everything as per example in ISO 8601 but make sure the system is set to the correct Globale. After chaining it make sure to restart Chrome, Firefox.. not sure about IE or other browsers.
  • myhrmans
    myhrmans almost 10 years
    @MarjanVenema - I've hooked into the Model Metadata and I add this to the DisplayFormatString and to the EditFormatString.
  • Marjan Venema
    Marjan Venema almost 10 years
    @SwampyFox: Thanks! (Any references on how to do this?)
  • myhrmans
    myhrmans almost 10 years
    @MarjanVenema- I've used the "ExtensibleModelMetadataProvider" from Matt Honeycutt's FailTracker (github.com/MattHoneycutt/Fail-Tracker). Look under the Infrastructure Folder to the ModelMetadata. I've used those classes and then created an filter implementation of IModelMetadataFilter. When the TransformMetadata method is called, you can then edit the "DisplayFormatString" and "EditFormatString" properties of the metadata. Hope this gets you in the right direction (btw, there is a great pluralsight video that uses Fail-Tracker)
  • Tetsujin no Oni
    Tetsujin no Oni over 9 years
    Downvoting for browser detection in server side code.
  • Rahul Nikate
    Rahul Nikate over 9 years
    Its not working for me. Year part in date picker accepting upto 6 digits. How can i restrict to 4 digits. Heres my code : [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)] [DataType(DataType.Date, ErrorMessage = "Please enter a valid date in the format MM/DD/YYYY")] [Display(Name = "Date of Birth:")] [Required] public string DOB { get; set; }
  • cmxl
    cmxl about 9 years
    thanks! fixes the mentioned chrome "issue" and of course you can have another displayformat on your datetime property!
  • Shaiju T
    Shaiju T about 9 years
    thank you finally this worked, i tried string.Format("{0}/{1}/{2}") to get dd/mm/yyyy format, and it works fine, i used database first method but DisplayFormat didn't worked with partial class, don't know why?, anyway anyone if needed try this method , i didn't try but if anyone needed , hope it helps
  • Richard McKenna
    Richard McKenna over 8 years
    Yes great solution. This provides an excellent work around for those of us not in the US.
  • dsghi
    dsghi over 8 years
    I think this is the best solution to the problem, it fixes just the editor issue and doesn't affect existing display formatting.
  • Atron Seige
    Atron Seige over 8 years
    Using "Date.cshtml" instead of "DateTime.cshtml" was the magic answer! It works in MVC 4 as well.
  • Guilherme de Jesus Santos
    Guilherme de Jesus Santos about 6 years
    Great! Obrigado.
  • MelloG
    MelloG about 6 years
    Maaann, i was searching for this and I finally got it! thank you!!
  • Just a HK developer
    Just a HK developer almost 6 years
    As there is @ at the beginning, that @Value = @Model.Property... still need that @? Do you mean just new { Value = Model.Property...?
  • brichins
    brichins over 5 years
    Had to stick with DateTime.cshtml instead of the recommended Date, but after a couple tweaks it worked great! One of my key changes was using the pre-formatted value (generated using the model property's specified DisplayFormat), which made the last line: @Html.TextBox(ViewData.TemplateInfo.HtmlFieldPrefix, ViewData.TemplateInfo.FormattedModelValue, htmlAttributes)
  • Greg Barth
    Greg Barth over 3 years
    Great answer! I had the same problem with 0:MM/dd/yyyy instead of the other way around - 0:yyyy-MM-dd. This worked (the commented-out annotations is what I originally had in my model:[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] //[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)] [DataType(DataType.Date)]
  • Zimano
    Zimano almost 3 years
    Can confirm, @user3454439