问题
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