ChatGPT解决这个技术问题 Extra ChatGPT

使用数据注释分配 DateTime 的格式?

我的视图模型中有这个属性:

[DataType(DataType.DateTime)]
public DateTime? StartDate { get; set; }

如果我想显示日期,或者用日期填充文本框,我有这些:

<%: Model.StartDate %>

<%: Html.TextBoxFor(m => m.StartDate) %>

每当显示日期时,它都会显示为:01/01/2011 12:00:00 AM

但我只想显示 01/01/2011

有没有办法应用带有数据注释的显示格式?我不想去每个显示日期的实例,并添加一些代码来格式化它。


D
David Fox

尝试使用以下标签对其进行标记:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]

刚试过,它仍然在TextBox中显示时间,以及它刚刚显示在页面上的时间。
@Steven:如果您还没有,您可以尝试删除 [DataType(DataType.DateTime)] 吗?
DisplayFormat 仅适用于 EditorForDisplayFor 助手。
很好的答案 - 我错过了“ApplyFormatInEditMode”参数。
我能够通过 Html.TextBoxFor 中的格式参数解决这个问题。通过将其设置为 @Html.TextBoxFor(model => model.YOUR_DATE, "{0:MM/dd/yyyy}"),我能够获得要显示的日期。在这里找到这个 [stackoverflow.com/a/14529347/2938775]
r
rk1962

你试过这个吗?

[DataType(DataType.Date)]

如果浏览器支持,这也将启用 HTML5 日期选择器支持。
H
Hasib Tarafder

在 mvc 4 中,您可以使用 TextBoxFor 轻松完成以下操作。

@Html.TextBoxFor(m => m.StartDate, "{0:MM/dd/yyyy}", new { @class = "form-control default-date-picker" })

因此,您不需要在模型或视图模型类中使用任何数据注释


是的,这些 DataAnnotations 非常适合 EditorFor 助手,但是,当使用 IEnumerable(Of Entity) 渲染自定义网格时,您必须使用 .TextBoxFor ,这是我的问题。谢谢
C
CodeArtist

如果您的数据字段已经是 DateTime 数据类型,则无需使用 [DataType(DataType.Date)] 进行注释;只需使用:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]

在 jQuery 上,为您的日历使用 datepicker

    $(document).ready(function () {
        $('#StartDate').datepicker();
    });

在您的 HTML 上,使用 EditorFor 助手:

    @Html.EditorFor(model => model.StartDate)

"如果您的数据字段已经是 DateTime 数据类型,则不需要使用 [DataType(DataType.Date)]" =>这很有帮助
但是对于 web api,显示格式不强制执行 DataFormatString = "{0:MM/dd/yyyy}"(即使请求正文具有其他格式,即 {"dob":"31/12/1990"},也没有得到任何 400)
C
Chirag

应用 DataAnnotation,如:

[DisplayFormat(DataFormatString = "{0:MMM dd, yyyy}")]

R
Renatto Machado

使用它,但它是一个完整的解决方案:

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

M
Md. Ilyas Hasan Mamun

评论后

          // [DataType(DataType.DateTime)] 

使用数据注释属性:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]

以下链接的 STEP-7 可以帮助您...

http://ilyasmamunbd.blogspot.com/2014/12/jquery-datepicker-in-aspnet-mvc-5.html


P
Philip Stratford

这对我行得通

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

c
collusionbdbh

使用 EditorFor 而不是 TextBoxFor


A
Arkox

这是我最喜欢在模型中使用注释的方法:

[DisplayFormat(DataFormatString = "{0:dd/MM/yyy}")]

佚名

在创建模型时使用以下代码设置您的属性我认为您的问题将得到解决..时间不会出现在数据库中。您不需要添加任何注释。

private DateTime? dob;
        public DateTime? DOB
        {
            get
            {
                if (dob != null)
                {
                    return dob.Value.Date;
                }
                else
                {
                    return null;
                }

            }
            set { dob = value; }
        }