问题
I have this in a view model:
[Required]
[Display(Name = "Date of birth")]
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime DateOfBirth { get; set; }
And on the form:
<div class="form-group">
@Html.LabelFor(model => model.DateOfBirth, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.DateOfBirth, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.DateOfBirth, "", new { @class = "text-danger" })
</div>
</div>
Works nicely in all browsers apart from Chrome which only displays "dd/MM/yyyy" instead of populating the field with the value from the model.
So I tried changing the date format in the ViewModel:
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
Chrome starts showing the model value in the format dd/MM/yyyy (potentially due to my local region settings?), but all the other browsers start showing the yyyy-MM-dd format.
I get that it's an international recognised standard, but being an Australian website the design we were working with was in the format of dd/MM/yyyy.
Can I get it working so that all the browsers show dd/MM/yyyy without needing to resort to:
@Html.TextBoxFor(model => model.DateOfBirth, new { htmlAttributes = new { @class = "form-control" }, @Value = Model.DateOfBirth.ToString("dd/MM/yyyy") })
Which means that Chrome doesn't provide the date picker functionality.
Using latest version of MVC, with a c# view model. Looks like Opera behaves similarly to Chrome.
回答1:
It appears Chrome only accepts the format as yyyy-MM-dd
, so the following will work
[Required]
[Display(Name = "Date of birth")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime DateOfBirth { get; set; }
It will then display the assigned date (using your regional settings) rather than the date string. I guess that has an advantage in that a user in another culture would see the date in their culture rather than yours.
This actually in accordance with the specifications
This does not help much if you are also using @Html.DisplayFor(m=> m.DateOfBirth)
. One workaround would be to create a DisplayTemplate DateTime.cshtml
that formats the date string using .ToString("dd/MM/yyyy")
回答2:
We've ended up just using separate drop down lists for the day, month, year fields. I imagine the other option would have been to find a datepicker plugin that worked in all browsers (and on mobile devices). Annoying!
来源:https://stackoverflow.com/questions/25302782/date-inconsistency-across-browsers-mvc-5-date-from-model