Try adding this attribute to your MyDate
property:
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
Though setting the culture in the web.config should do it, this should force it into that format.
UPDATE
Ok, so the above answer doesn't really solve the issue, though it is important if you do want to change the format of how the date is initially displayed. An important note is that the DisplayFormat
attribute is not picked up by the TextBoxFor
helper but it is by the EditorFor
helper.
Anyway, on to the real solution. The problem is the jQuery validation not accounting for the culture when parsing a date. If you turn off the client side validation the date is parsed just fine on the server that is aware of the culture.
The fix is to override the jQuery validation for date and include an additional jQuery globalization plugin. You can find the globalize plugin here. You can also easily download the plugin using the Nuget Package Manager as well. I just opened the package manager, selected the Online tab on the left and typed "globalize" into the search and it was the first result. Once you have it installed I included these two files:
globalize.js
globalize.culture.en-AU.js
You can either include them directly using a script tag or place them in a bundle, perhaps with the other jQuery validation files.
Once you have those you will need to add the following script to override the jQuery validation for date:
<script type="text/javascript">
$(function () {
$.validator.methods.date = function (value, element) {
Globalize.culture("en-AU");
// you can alternatively pass the culture to parseDate instead of
// setting the culture above, like so:
// parseDate(value, null, "en-AU")
return this.optional(element) || Globalize.parseDate(value) !== null;
}
});
</script>
And that's it, that should do the trick. I credit this solution to this answer: JQuery Validation and MVC 3. How to change date format I just also wanted to provide some more explanation specific to your issue.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…