Shorten this if statement in Razor to one line

前端 未结 4 900
情书的邮戳
情书的邮戳 2021-02-18 13:08

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

@if(SiteMap.CurrentNode.Title == \"Contact\")
{
    @:
相关标签:
4条回答
  • 2021-02-18 13:54

    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" : "")">
    
    0 讨论(0)
  • 2021-02-18 14:06

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

    @Html.Raw((SiteMap.CurrentNode.Title == "Contact") ? "<div class='contact'>" : "")
    
    0 讨论(0)
  • 2021-02-18 14:09

    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

    0 讨论(0)
  • 2021-02-18 14:10

    This will work

    Razor Syntax

    @(SiteMap.CurrentNode.Title == "Contact" ? "<div class='contact'>")
    
    0 讨论(0)
提交回复
热议问题