Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I reduce razor code to just few lines?

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")}
like image 994
Junior Mayhé Avatar asked Feb 17 '11 13:02

Junior Mayhé


People also ask

What is Razor markup?

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.

What is @: In Cshtml?

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.


1 Answers

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.

like image 161
Darin Dimitrov Avatar answered Oct 20 '22 21:10

Darin Dimitrov