html - 全球化文化如何影响 MVC 日期
问题描述
我有以下模型:
public class Appointment
{
[DataType(DataType.Date)]
public DateTime Date { get; set; }
}
看法:
@model ModelValidation.Models.Appointment
Appointment Date: @Html.EditorFor(m => m.Date)
和控制器:
public ViewResult MakeBooking()
{
return View(new Appointment { Date = DateTime.Now });
}
我已将此添加到 Web.config:
<system.web>
...
<globalization culture="en-AU" uiCulture="en-AU"/>
</system.web>
这会产生以下 HTML 正文:
Appointment Date: <input class="text-box single-line"
data-val="true" data-val-date="The field Date must be a date."
data-val-required="The Date field is required."
id="Date" name="Date" type="date" value="25/09/2018" />
页面上的文本框如下所示:
我的第一个问题是,为什么它显示“dd/mm/yyyy”而不是“25/09/2018”?
当我更改<globalization culture="en-AU" uiCulture="en-AU"/>
为<globalization culture="en-US" uiCulture="en-US"/>
唯一的区别是HTML生成value="09/25/2018"
而不是value="25/09/2018"
为什么它不在网页的文本框中显示“mm/dd/yyyy”?
我正在使用 MVC5 和 Chrome,并且位于澳大利亚。
解决方案
The [DataType(DataType.Date)]
attribute generates type="date"
when used with EditorFor()
which in turn generates the browsers HTML5 datepicker.
The HTML specifications require that the the date be in ISO format, so you need to add a [DisplayFormat]
attribute
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime Date { get; set; }
and the date will then be displayed in the users culture (which is the purpose of of the HTML5 datepicker).
Alternatively, you can use
@Html.TextBoxFor(m => m.Date, "{0:yyyy-MM-dd}")
推荐阅读
- python - 检查是否在另一个字符串中找到一个字符串时,如何限制 Python if-in 语句的结果?
- r - 在 R Shiny 中使用 ggplot2 绘制面板可视化
- java - Java中的非实例对象无用吗?
- python - 从另一个列表替换 Python 列表中的项目
- c - 如何读取 C 中的音频(即 FFT 或存储桶)?
- excel - 打印已打开 Internet Explorer
- css - 如何强制单词始终以大写字母显示?
- reactjs - 设置状态时将状态中的数组替换为 1
- python - 当每一行都是字典列表时,如何从数据框中提取某些特征
- ios - 没有动画用于在 UISplitViewController 中显示和隐藏主 UIViewController 以进行尾随演示(primaryEdge = .trailing)