Shorten this if statement in Razor to one line

2019-04-18 03:04发布

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">
}

标签: razor
3条回答
可以哭但决不认输i
2楼-- · 2019-04-18 03:27

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

@Html.Raw((SiteMap.CurrentNode.Title == "Contact") ? "<div class='contact'>" : "")
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-04-18 03:38

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" : "")">
查看更多
混吃等死
4楼-- · 2019-04-18 03:44

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

查看更多
登录 后发表回答