ViewModel中未呈现ViewModel DisplayFormat数据注释 [英] ViewModel DisplayFormat Data Annotation not rendered in View

查看:29
本文介绍了ViewModel中未呈现ViewModel DisplayFormat数据注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using ASP.NET 5 Web Application Template I am trying to render a date in short date format. My viewmodel looks like this

    [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以长日期格式呈现.如何获取以短日期格式呈现日期的视图?

However @Model.SubscriptionExpires renders in long date format. How do I get the view to render the date in short date format?

推荐答案

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

You're directly outputting the date to the page, there is no opportunity for your data annotations to be considered.

HTML助手会查看这些注释,因此您可以轻松地做到这一点:

HTML helpers look at those annotations, so you could simply do this:

@Html.DisplayFor(model => model.SubscriptionExpires)

或者像这样简单地格式化日期:

Alternatively simply format the date like this:

@Model.SubscriptionExpires.ToShortDateString()

这篇关于ViewModel中未呈现ViewModel DisplayFormat数据注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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