跨浏览器的日期不一致 - MVC 5来自模型

时间:2014-08-14 07:53:16

标签: asp.net-mvc-5

我在视图模型中有这个:

[Required]
[Display(Name = "Date of birth")]
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime DateOfBirth { get; set; }

在表格上:

<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>

除Chrome之外的所有浏览器都能很好地工作,只显示“dd / MM / yyyy”,而不是使用模型中的值填充字段。

所以我尝试在ViewModel中更改日期格式:

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]

Chrome开始以dd / MM / yyyy格式显示模型值(可能是由于我的本地区域设置?),但所有其他浏览器都开始显示yyyy-MM-dd格式。

我认为这是一个国际公认的标准,但作为一个澳大利亚网站,我们正在使用的设计采用dd / MM / yyyy格式。

我可以让它工作,以便所有浏览器显示dd / MM / yyyy而无需诉诸:

@Html.TextBoxFor(model => model.DateOfBirth, new { htmlAttributes = new { @class = "form-control" }, @Value = Model.DateOfBirth.ToString("dd/MM/yyyy") })

这意味着Chrome不提供日期选择功能。

使用最新版本的MVC,使用c#视图模型。看起来Opera的行为与Chrome类似。

2 个答案:

答案 0 :(得分:1)

Chrome似乎只接受yyyy-MM-dd格式,因此以下内容可以正常使用

[Required]
[Display(Name = "Date of birth")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime DateOfBirth { get; set; }

然后它将显示指定的日期(使用您的区域设置)而不是日期字符串。我想这有一个优势,即另一种文化中的用户会在他们的文化中看到日期而不是你的日期。

这实际上符合specifications

如果您还使用@Html.DisplayFor(m=> m.DateOfBirth),这没有多大帮助。一种解决方法是创建一个DisplayTemplate DateTime.cshtml,使用.ToString("dd/MM/yyyy")格式化日期字符串

答案 1 :(得分:0)

我们最终只使用了日,月,年字段的单独下拉列表。我想另一个选择是找到一个适用于所有浏览器(以及移动设备)的datepicker插件。讨厌!

相关问题