@ Html.DisplayFor - 日期格式(" MM / DD / YYYY") [英] @Html.DisplayFor - DateFormat ("mm/dd/yyyy")

查看:1150
本文介绍了@ Html.DisplayFor - 日期格式(" MM / DD / YYYY")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的剃刀code,我想有 MM / DD / YYYY 日期格式:

I have the following razor code that I want to have mm/dd/yyyy date format:

Audit Date: @Html.DisplayFor(Model => Model.AuditDate)

我曾尝试不同的方法,但数量都不在我的情况接近的作品

I have tried number of different approaches but none of that approaches works in my situation

我AuditDate是的DateTime?键入

my AuditDate is a DateTime? type

我已经试过这样的事情,并得到这个错误:

I have tried something like this and got this error:

@Html.DisplayFor(Model => Model.AuditDate.Value.ToShortDateString())

更多信息:模板只能与现场访问,访问属性,一维数组的索引,或单参数自定义索引前pressions使用

Additional information: Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

试过这个:

@Html.DisplayFor(Model => Model.AuditDate.ToString("mm/dd/yyyy"))

没有过载方法'的ToString'需要1个参数

No overload for method 'ToString' takes 1 arguments

推荐答案

如果您使用 DisplayFor ,那么你就必须要么通过 DisplayFormat 属性或使用自定义显示模板。

If you use DisplayFor, then you have to either define the format via the DisplayFormat attribute or use a custom display template.

[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime? AuditDate { get; set; }

或创建视图视图\\共享\\ DisplayTemplates \\ DateTime.cshtml

@model DateTime?
if (Model.HasValue)
{
    @Model.Value.ToString("MM/dd/yyyy")
}

这将适用于所有的DateTime S,不过,甚至是那些你在哪里编码的时候也是如此。如果你想让它仅适用于日期仅属性,然后使用视图\\共享\\ DisplayTemplates \\ Date.cshtml 数据类型你的财产属性:

That will apply to all DateTimes, though, even ones where you're encoding the time as well. If you want it to apply only to date-only properties, then use Views\Shared\DisplayTemplates\Date.cshtml and the DataType attribute on your property:

[DataType(DateType.Date)]
public DateTime? AuditDate { get; set; }

最后的选择是只不使用 DisplayFor 而直接渲染属性:

@if (Model.AuditDate.HasValue)
{
    @Model.AuditDate.Value.ToString("MM/dd/yyyy")
}

这篇关于@ Html.DisplayFor - 日期格式(" MM / DD / YYYY")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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