c# mvc

Chrome Displaying Format In Faded Gray Text for Model Property with DataType.Date and DataFormatString = "{0:dd/MM/yyyy}"

Solution 1:

Remove [DataType(DataType.Date)]

Limitations of Solution 1:

- chrome won't show datepicker in input (edit mode)

- saving the date does not work

Solution 2:

When you decorate a model property with [DataType(DataType.Date)] the default template in ASP.NET MVC 4/5 generates an input field of type="date". 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 yyyy-MM-dd, as defined in [RFC 3339].

Therefore, the solution is:

[DataType(DataType.Date)]

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

public DateTime Birth { get; set; }

Limitations of Solution 2:

- date is not displayed in local culture format, such as dd/MM/yyyy.

Solution 3:

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

@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)}

Limitations of Solution 3:

- None

This problem and solutions is described in many forums. For instance, solutions 2 and 3 were gathered from http://stackoverflow.com/questions/12633471/mvc4-datatype-date-editorfor-wont-display-date-value-in-chrome-fine-in-interne

Solution 4:

If you need DateTime, then

[DataType(DataType.DateTime)]

[DisplayFormat(DataFormatString = "{0:yyyy-MM-ddTHH:mm}", ApplyFormatInEditMode = true)]