【问题标题】:ViewModel DisplayFormat Data Annotation not rendered in ViewViewModel DisplayFormat 数据注释未在视图中呈现
【发布时间】:2016-04-17 23:14:14
【问题描述】:

使用 ASP.NET 5 Web 应用程序模板 我正在尝试以短日期格式呈现日期。我的视图模型看起来像这样

    [Display(Name = "Subscription Expires")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
    public DateTime? SubscriptionExpires { get; set; }

我的视图是这样的

    <dt><label asp-for="SubscriptionExpires"></label>:</dt>
<dd>
    @Model.SubscriptionExpires
</dd>

但是@Model.SubscriptionExpires 以长日期格式呈现。如何让视图以短日期格式呈现日期?

【问题讨论】:

    标签: asp.net-core asp.net-core-mvc


    【解决方案1】:

    您直接将日期输出到页面,没有机会考虑您的数据注释。

    HTML 助手会查看这些注释,因此您可以简单地这样做:

    @Html.DisplayFor(model =&gt; model.SubscriptionExpires)

    也可以像这样简单地格式化日期:

    @Model.SubscriptionExpires.ToShortDateString()

    【讨论】:

    • 谢谢@Mister Epic。 'ToShortDateString()' 不能用于可为空的类型,但 '@Html.DisplayFor(model => model.SubscriptionExpires)' 成功了。
    猜你喜欢
    • 1970-01-01
    • 2011-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多