Shorten this if statement in Razor to one line

The shortest possible way to do is like:

@(SiteMap.CurrentNode.Title == "Contact" ? "<div class='contact'>" : "")

or

@(SiteMap.CurrentNode.Title == "Contact" ? @"<div class=""contact"">" : "")

or even shorter if you don't repeat your html code

<div class="@(SiteMap.CurrentNode.Title == "Contact" ? "contact" : "")">

There might be an even simpler solution but this should work:

@Html.Raw((SiteMap.CurrentNode.Title == "Contact") ? "<div class='contact'>" : "")

Another way would be:

@if(SiteMap.CurrentNode.Title == "Contact") { <text><div class="contact"></text> }

I personally find it more readable than the ternary operator, but this is personal

Tags:

Razor