**UPDATE
I just realized that the date is not getting data-binded during post at all, unless I use firefox.
Why would the browser affect the databinding on server side?
I feel like I’m taking crazy pills
My problem is that I have a JQuery date picker that seems to be formatted the right way (mm/dd/yyyy) but when the value gets posted to the server, the months and days are switched.
The date property is added to the page like this (it’s hidden just so it can bind during posts. The problem is the same if it were a simple text box):
<input type="hidden" name="SearchByDate" id="SearchByDate" value="<%: ((DateTime)Model.SearchByDate).ToString(Web.Common.Config.GetDateFormatBase) %>" />
In my view model, I specify the date format like this:
[DisplayFormat(DataFormatString = Common.Config.GetDateFormat,
ApplyFormatInEditMode = true)]
public DateTime? SearchByDate { get; set; }
My javascript datepicker is formatted like this:
$("#appointmentDateDiv").datepicker({
------> dateFormat: "<%= Web.Common.Config.GetDateFormatJavascript %>",
changeMonth: true,
onSelect: function (dateText, inst) {
$("#SearchByDate").val(dateText);
$("form").submit();
}
});
I actually sepcify the formats in a common class like this:
public const string GetDateFormatBase = @"MM/dd/yyyy";
public const string GetDateFormat = @"{0:" + GetDateFormatBase + "}"; //This is for annotations
public const string GetDateFormatJavascript = "mm/dd/yy";
As you can see, the formats are all the sam:month day year.
Everything looks good when I first load a page like this, so the datepicker lets me select a date in the right format. Then I post and if I step through my code everything still looks fine. I even re-format the date to make sure before I return to the view. But the month and day always get switched.
The strangest thing though, is that everythiing works fine in Firefox. It fails in IE, Chrome, and Opera. But I can’t see why…
Thanks, for the help guys.
@JohnKoerner, you were right, it was a l18n problem. My Firefox was set to en-US and my other browsers were en-CA. I didn’t think they’d be different date formats but they were. This caused problems during model-binding. My solution was to use invariant culture to parse all dates in a custom model binder. I got the idea from here.
But, I was already using a different model-binder from here. And I modified the relevant piece of code like this
where T would we the datetime that is being parsed.
Another thing was to make sure to register the custom model binder for both DateTime and DateTime? like this: