首页 > 解决方案 > 全球化文化如何影响 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,并且位于澳大利亚。

标签: htmlasp.netasp.net-mvcasp.net-mvc-5

解决方案


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}")

推荐阅读