日期输入标签帮助程序未显示数据库中的日期 [英] Date input tag helper is not showing the date from database

查看:86
本文介绍了日期输入标签帮助程序未显示数据库中的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在编辑视图中使用以下代码时,它不会显示模型中的日期.

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?

为了显示具有正确格式的字段,请删除 [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; }

如果要使用带日期选择器的自定义日期格式,则需要使用一些自定义JavaScript解决方案.

If you want to have custom date format with datepicker, you need to use some custom JavaScript solution.

更新: 如果model属性是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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆