How to make date visible in Chrome native datepicker while it binds from Model in MVC4

Introduction

When we want to bind a date field from Model to View in MVC4 and try to see it in Chrome, it will not display the date while it works fine with Internet Explorer. So this tip will help you to resolve this problem.

How to use

Suppose you have a property StartDate in your model:

[DataType(DataType.Date)]public DateTime StartDate

Now if you have a view with the following code to edit StartDate and here I am using the Html.EditorFor helper class so this helper class by default generates the input field with type date.

    <%: Html.LabelFor(model => model.StartDate) %>
    <%: Html.EditorFor(model => model.StartDate) %>  
 
  <%: Html.ValidationMessageFor(model => model.StartDate) %>

The reason behind this is that when we add a property in the model with annotation [DataType( DataType.Date)], then ASP.NET MVC4 by default generates an input field with type="date" and Chrome has supported HTML5 so it will render as a date picker which is supported by the default format of date like "yyyy/mm/dd".

So we need to change the format of date in the model itself by giving the following annotation:

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

So finally, the model Property will look like:

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

Summary

 I know there are a lot of ways to achieve this, but I find this method most easy and fruitful, that's why I am sharing it with all.