Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

My model class property looks like this

   public DateTime PurchaseDate { get; set; }

and inside view

 @Html.TextBoxFor(model => model.PurchaseDate, new { @class = "form-control date-picker" })
 @Html.ValidationMessageFor(model => model.PurchaseDate)

and I am giving a date like this in form

19/06/2015

But it gives validation message and not allows page to be submitted, message is like this

The field PurchaseDate must be a date.

if I give date in mm/dd/yyyy format it works. Can anyone point out what I am doing wrong here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
361 views
Welcome To Ask or Share your Answers For Others

1 Answer

If you want to explicitly set the expected date format for your model property then you can do this using the DisplayAttribute

[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime PurchaseDate { get; set; }

Otherwise, the current culture of the server would be used (which in your case happens to be MM/dd/yyyy).


It appears that in order for client-side validation to respect the DataFormatString we need to use EditorFor in place of TextBoxFor

 @Html.EditorFor(model => model.PurchaseDate, new { @class = "form-control date-picker" })
 @Html.ValidationMessageFor(model => model.PurchaseDate)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...