Conditional link in Razor

I have several tabs, and I want to say: "If they are currently on the page that this tab links to, make it span. Otherwise, make it a link." In a pseudo razor, it will look like this:

@if(CurrentlyOnThisPage) { <span> } else { <a> } Tab Content @if(CurrentlyOnThisPage){ </span> } else { </a> } 

Razor (correctly) notes that I am not closing my start tags, and therefore cannot parse this syntax. If the contents of the tab were small, I could use Html.ActionLink , but I have a few lines, and I would like to keep the benefits of the HTML editor, rather than putting it in a line. Is there any way to do this?

+4
source share
3 answers

How about something like that?

 @{ var linkOrSpan= CurrentlyOnThisPage ? "span" : "a"; } <@linkOrSpan><text>Tab Content</text></@linkOrSpan> 

No errors when closing tags with this.

Looks a little cleaner too ihmo.

NTN

+4
source

You can write tags in literal text to prevent Razor parsing:

 @:<span> 
+7
source

Or just write it explicitly:

 @if(CurrentlyOnThisPage) { <span>tabcontent</span> } else { <a>tabcontent</a> } 
+2
source

Source: https://habr.com/ru/post/1341676/


All Articles