ViewModel DisplayFormat Data Annotation not rendered in View

瘦欲@ 提交于 2019-12-11 11:52:43

问题


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; }

My view looks like this

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

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


回答1:


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

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()



来源:https://stackoverflow.com/questions/34758911/viewmodel-displayformat-data-annotation-not-rendered-in-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!