So I have this asp.net application built using razor and C# and I can't get the validation for date time to work correctly.
Here are the relevant sections of my app.
public class EmployeeDto
{
...
[Required]
[DataMember]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")] // from what I understand this should format the date on the view ackording to the string
public Nullable<DateTime> inDate { get; set; }
...
[Required]
[DataMember]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public Nullable<DateTime> birthDate { get; set; }
[DataMember]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public Nullable<DateTime> createdDate { get; set; }
...
}
This DTO is also used as a view model.
On the add employee view, we use a date-picker to edit the first two dates. The third is hidden.
Here's what the view looks like
@model StratecEMS.Application.DTO.EmployeeDto
<style type="text/css">...</style>
<script type="text/javascript">
$(function () {
$("#birthDate").datepicker({ dateFormat: 'dd/mm/yy' });
$("#inDate").datepicker({ dateFormat: 'dd/mm/yy' });
});
...
</script>
...
<fieldset>
<legend>New Employee Details</legend>
@using (Html.BeginForm("AddEmployee", "Administration", FormMethod.Post, new { id = "AddEmployeeForm" }))
{
@Html.HiddenFor(model => Model.createdDate)
<div class="editor-label">
@Html.Label("In Date:")
@Html.EditorFor(model => model.inDate)
@Html.ValidationMessageFor(model => model.inDate)
</div>
<div class="editor-label">
@Html.Label("Birthdate:")
@Html.EditorFor(model => model.birthDate)
@Html.ValidationMessageFor(model => model.birthDate)
</div>
}
</fieldset>
Now here's my problem: On my PC I have the date in international format "yyyy-MM-dd". On the application we need the date to always be in a custom format "dd/MM/yyyy" however the validation is always done in the US format "MM/dd/yyyy" and I'm at a loss why this happens.
To make things even stranger after adding the DisplayFormat attribute to the DTO, the two dates that are displayed on my UI are shown in this format "dd-MM-yyyy". WTF!?! but the validation is sill done in the US format.
I can get around the validation for the birthDate and inDate by entering the dates in the US format in the text-boxes, however there is no such workaround for createdDate which is always hidden and remains in the in the international format.
I've also tried to change the culture of the application by setting the thread culture in the Global.asax Application_Start method using this piece of code
var culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
culture.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
However this too seems not to work.
If you had the patience to read this until the end. Do you happen to know a good solution for this predicament?