在@Html.EditorFor 助手中只显示日期 [英] show only the date in @Html.EditorFor helper

查看:22
本文介绍了在@Html.EditorFor 助手中只显示日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试填充 @Html.EditorFor 助手.我创建了一个具有以下属性的视图模型

I am trying to populate @Html.EditorFor helper. I have created a view model with the below property

[DataType(DataType.Date, ErrorMessage="Date only")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yy}", ApplyFormatInEditMode = true)]
public DateTime? YearBought { get; set; }

我的助手设置如下(a)

and my helper is set up as below (a)

@Html.ValidationMessageFor(m => m.YearBought)
@Html.EditorFor(model => model.YearBought, new { @type = "date" })

我也试过(b)

@Html.ValidationMessageFor(m => m.YearBought)
@Html.EditorFor(model => model.YearBought.Value.Date)

使用上述格式 (a) 不显示任何内容.使用上述格式(b) 12/05/2014 00:00:00 以文本框格式显示.

Using the above format (a) nothing is displayed. Using the above format (b) 12/05/2014 00:00:00 is displayed in textbox format.

我正在尝试实现不显示时间的日期选择器格式

I am trying to achieve a datepicker format without a time displayed

我已经查看了其他几个问题,但看不出我做了什么不同的事情.

I have reviewed several other questions but cant see what i've done different.

当我查看我的数据库时,该值保存为 2014-05-12 并且当我保存该值时,EditorFor 助手会生成所需的输入工具

When I look in my database, the value is save as 2014-05-12 and when I am saving the value the EditorFor helper generates the required input facility

首先 第二 第三个......名单还在继续

first second third....the list goes on

编辑刚刚在 chrome 开发工具中打开了控制台,所以这条消息

EDIT just opened the console in chrome dev tools and so this message

指定值12/05/14"不符合要求的格式,yyyy-MM-dd"

The specified value "12/05/14" does not conform to the required format, "yyyy-MM-dd"

我以为 DisplayFormat(DataFormatString = "{0:dd/MM/yy}" 定义了如何显示我的日期?

I thought DisplayFormat(DataFormatString = "{0:dd/MM/yy}" was defining how to display my date?

推荐答案

使用type="date"

[DataType(DataType.Date, ErrorMessage="Date only")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? YearBought { get; set; }

这将显示浏览器文化中的日期.

This will display the date in the browsers culture.

注意不需要添加@type = "date".由于 DataType 属性,EditorFor() 方法将添加它.另请注意,type="date" 仅在 Chrome 中受支持(FireFox 和 IE 只会生成普通文本框)

Note there is no need to add @type = "date". The EditorFor() method will add that because of the DataType attribute. Note also that type="date" is only supported in Chrome (FireFox and IE will just generate a normal textbox)

如果您确实想在标准文本框中显示格式 dd/MM/yyyy 那么您可以使用

If you do want to display the format dd/MM/yyyy in a standard textbox then you can use

@Html.TextBoxFor(m => m.YearBought, "{0:dd/MM/yyyy}")

这篇关于在@Html.EditorFor 助手中只显示日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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