After reading a lot of answers here at stackoverflow I came to this solution:
In the model I introduce a new, not mapped property:
...
[NotMapped]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime GeburtsdatumChromeEdit
{
get { return this.Geburtsdatum; }
set { this.Geburtsdatum = value; }
}
...
This is necessary to add the dataannotiation DisplayFormat
with the format Chrome wants. It pipes the value to the original property.
In the view I doubled the Input for the date and encapsulated the two groups by div's with special classes:
<div class="date4Normal">
@*Tut nicht in Chrome, da dieser dann einen Input vom Type "Date" verwendet und dieser verlangt dann ein Normdatum yyyy-mm-dd*@
@Html.EditorFor(model => model.Geburtsdatum)
@Html.ValidationMessageFor(m => m.Geburtsdatum, String.Empty, new {@class = "text-danger"})
</div>
<div class="date4Chrome">
@Html.EditorFor(model => model.GeburtsdatumChromeEdit)
@Html.ValidationMessageFor(m => m.GeburtsdatumChromeEdit, String.Empty, new { @class = "text-danger" })
@*@Html.TextBoxFor(model => model.Geburtsdatum, "{0:dd.MM.yyyy}")
@Html.ValidationMessageFor(m => m.Geburtsdatum, String.Empty, new { @class = "text-danger" })*@
</div>
With a function I found on stackoverflow (How can I tell if a browser supports <input type='date'>) I can detect if the actual browser uses date-input:
function checkDateInput() {
var input = document.createElement('input');
input.setAttribute('type', 'date');
var notADateValue = 'not-a-date';
input.setAttribute('value', notADateValue);
return (input.value !== notADateValue);
}
With the next function I remove the input-blocks I do not need:
function switchForChrome() {
var isChrome = checkDateInput();
if (isChrome) {
$('.date4Normal').remove();
} else {
$('.date4Chrome').remove();
}
};
In the $(document).ready
function I call the switchForChrome();
.
At this point it seems to work, but the validation of the date allways failed.
So I add some code to work around (ASP.NET MVC 4 avoid generation of data-val-date for datetime):
if (checkDateInput()) {
$.validator.addMethod('date',
function (value, element) {
return true;
});
}
And finally it works.
For display I use the original property (Geburtsdatum
) so I get the language-specific format and for edit either the original property (IE, Firefox) or the new property GeburtsdatumChromeEdit
(Chrome, Opera).