DisplayFormat停止在Chrome中显示英国日期?
我有我的模型的属性如下:DisplayFormat停止在Chrome中显示英国日期?
[DisplayName("Manufactured Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? DateManufactured { get; set; }
在我搭建的MVC核心观点我有这样的代码,以显示该值:
<input asp-for="LiftingItem.DateManufactured" class="form-control" />
在Chrome中,输入显示文本“ DD/MM/YYYY”,我得到的错误:
The specified value "09/02/2006" does not conform to the required format, "yyyy-MM-dd".
而在IE中,我得到的实际日期(例如 “2006年9月2日”)。我认为这种差异是因为Chrome使用HTML 5日期类型输入,因此需要“yyyy-MM-dd”格式的格式才能显示它?
如果我删除DisplayFormat
属性,果然它可以在Chrome中运行,但在IE中日期格式不正确(“yyyy-MM-dd”而不是“dd/mm/yyyy”)。
因此,看起来像使用非“yyyy-MM-dd”格式的DisplayFormat
可以阻止Tag Helpers的工作?有什么办法可以很好地兼容HTML 5兼容和旧版浏览器?
PS:我也尝试在视图中应用格式,而不是使用asp-format="{0:dd/MM/yyyy}
as described in this question,但这也阻止了它在Chrome中的工作。
编辑:我也可以删除[DataType(DataType.Date)]
,但是我没有在兼容HTML5的浏览器中使用datepicker,我一定会在移动设备上使用它。
是的,您可以将标签助手与DisplayFormat数据注释组合在一起。
So, it seems like using DisplayFormat with a non "yyyy-MM-dd" format stops the Tag Helpers working? Is there any way to get it working nicely for both HTML 5 compatible and older browsers?
刚刚从你的模型中删除[DataType(DataType.Date)]
并如期DisplayFormat(..)
语句将开始工作。
PS: I've also tried applying the formatting in the view instead using asp-format="{0:dd/MM/yyyy} as described in this question , but that also stops it working in Chrome.
您可以用比你的模型中指定的一个与asp-format
标签帮手结合DisplayFormat(..)
数据注解,如果你应要求,在一个特定的观点,不同的日期格式。
如果你在你的模型中的以下属性:与下面的代码行
[DisplayName("Manufactured Date")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? DateManufactured { get; set; }
和视图(例如详细视图):
@Html.DisplayFor(model => model.DateManufactured)
那么你的应用程序将显示日期的格式与数据注释中指定的格式相对应,即{0:dd/MM/yyyy}
。这里有一个例子:23/02/2017
。
如果在其他视图中添加(例如一个编辑视图)下面的代码行(请注意,我添加了一个“M”的月份格式):
<input asp-for="LiftingItem.DateManufactured" asp-format="{0:dd/MMM/yyyy}" class="form-control" />
然后asp-format
将优先于模型的数据表示法,并且您的应用程序用户可以在输入框中键入如下所示的日期:23/Feb/2017
。
嘿,谢谢你。删除'[DataType(DataType.Date)]'位的问题是你没有得到浏览器内置的datepicker,这在移动设备上很痛苦。理想情况下,我还希望在桌面上使用内置datepicker的浏览器(其中有一个)。 – tomRedox
@tomRedox是的你是对的。通过删除'[DataType(DataType.Date)]',类型将不会被设置为等于输入元素的日期,即在HTML代码''中不会得到这个。令人遗憾的是,事实上,对于Firefox,IE,Safari和旧版浏览器,您不会在上面使用数据注释获取日期选择器。 – Aquablue
谢谢,很高兴知道我不会生气!也许尝试使用数据注释是错误的方法,也许我应该查看某种条件逻辑来检查HTML5浏览器,并根据是否使用HTML5浏览器来设置“输入类型”。 – tomRedox