When you are POSTing to a controller action, the default model binder will use the current CultureInfo format of your server to parse the DateTime.
The current CultureInfo is determined by the <globalization>
setting in your web.config. For exmaple if you used the default value of auto
then the server will use the Accept-Language
request header of the browser to set it. SO it will depend in this case of the settings of the client web browser.
You can specify the culture info explicitly:
<globalization uiCulture="en" culture="en-US" />
Now the US culture will be used on the server for which the format of datetimes is MM/dd/yyyy
. So make sure you adjust to the culture you want.
If on the other hand you do not wish to specify some particular culture but instead have more flexibility of the format of some fields you could write a custom model binder as I illustrated in this post
.
Once you register the custom model binder for the DateTime type you will be able to decorate your view model property with the DisplayFormat
attribute and specify the desired format:
public partial class Book
{
public int BookId { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public System.DateTime? Published { get; set; }
}