Shorten this if statement in Razor to one line

2019-04-18 03:38发布

问题:

Can i shorten this to one line? I have tried various ways but can't quite get it right.

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

回答1:

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

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


回答2:

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



回答3:

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" : "")">


标签: razor