Can I reduce razor code to just few lines?
Can I reduce this razor code?
<li>
@{
if (@Model.Publica开发者_运维百科tionDate.HasValue) {
@Model.PublicationDate.Value.ToString("D", new System.Globalization.CultureInfo("fr-FR"))
}
else {
@:"pas disponible"
}
}
</li>
I was trying this but it doesn't work:
@{(@Model.PublicationDate.HasValue) ? (@Model.PublicationDate.Value.ToString("D")) : (@:"pas disponible")}
You could decorate your view model property with the [DisplayFormat]
attribute:
[DisplayFormat(DataFormatString = "{0:D}", NullDisplayText = "pas disponible")]
public DateTime? PublicationDate { get; set; }
and then your view simply becomes:
<li>
@Html.DisplayFor(x => x.PublicationDate)
</li>
So now it is reduced to a single and elegant line.
I assume you can use the ?:
operator to shorten it. If that's a good idea is a different question.
And you probably don't want to hard-code the locale with new System.Globalization.CultureInfo("fr-FR")
but use the locale from either a variable or the current locale of the thread.
精彩评论