Can I reduce this razor code?
<li>
@{
if (@Model.PublicationDate.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")}
What is Razor? Razor is a markup syntax that lets you embed server-based code (Visual Basic and C#) into web pages. Server-based code can create dynamic web content on the fly, while a web page is written to the browser.
CSHTML files use the @ symbol and Razor reserved directives to transition from HTML markup to C# code. Most CSHTML files are created in Microsoft Visual Studio. Visual Studio provides syntax highlighting and Intellisense code suggestions that help developers create CSHTML files.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With