日期输入标签助手未显示数据库中的日期 [英] Date input tag helper is not showing the date from database
问题描述
当我在编辑视图中使用以下代码时,它不显示模型中的日期.
When I use the following code in my edit view, it doesn't show the date from the model.
<input asp-for="OprettetDato" class="form-control"/>
模型的属性声明如下:
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0: dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime OprettetDato { get; set; }
并且值在模型中被传递
为什么这不起作用?
推荐答案
问题是你的模型属性上的属性 [DataType(DataType.Date)]
使输入标签助手产生 type="date"
HTML 属性,在 HTML5 中会导致固定的标准格式 - 请参阅此处的信息:有什么办法可以改变输入类型=日期"格式?
The problem is that attribute [DataType(DataType.Date)]
on your model property makes the input tag helper produce type="date"
HTML attribute, which in HTML5 causes fixed, standard format - see information here: Is there any way to change input type="date" format?
为了以正确的格式显示字段,remove [DataType(DataType.Date)]
属性就可以了.另外,为了在日期格式中使用正斜杠,您需要像这样对它们进行转义:
In order to display the field with proper format, remove [DataType(DataType.Date)]
attribute and you will be fine.
Additionaly, in order to have forward slashes in date format, you need to escape them like this:
[DisplayFormat(DataFormatString = @"{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime OprettetDato { get; set; }
如果您想使用 datepicker 自定义日期格式,则需要使用一些自定义 JavaScript 解决方案.
If you want to have custom date format with datepicker, you need to use some custom JavaScript solution.
更新:如果模型属性是 DateTime 对象,则更高版本的标签助手默认为输入日期类型.要允许自定义日期格式,请通过添加 [DataType(DataType.Text)]
Update:
Later versions of tag helpers default to the input date type if the model property is a DateTime object. To allow a custom date format ensure that the html input type is text by adding [DataType(DataType.Text)]
这篇关于日期输入标签助手未显示数据库中的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!