Xodarap
Xodarap

Reputation: 11849

Conditional link in Razor

I have some tabs, and I want to say "if they are currently on the page that this tab refers to, make this a span. Otherwise, make this a link." In pseudo-razor, that would look like this:

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

Razor (correctly) notes that I'm not closing my beginning tags, and so has trouble parsing this syntax. If the tab content was small, I could use Html.ActionLink, but I've got a few lines of stuff and I'd like to keep the benefits of the HTML editor rather than putting it all into a string. Is there any way to do this?

Upvotes: 4

Views: 3061

Answers (3)

Steven Striga
Steven Striga

Reputation: 1381

Or just write it out explicitly:

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

Upvotes: 4

SLaks
SLaks

Reputation: 887469

You can write the tags as literal text to prevent Razor from parsing them:

@:<span>

Upvotes: 8

DannyLane
DannyLane

Reputation: 2096

How about something like this?

@{
    var linkOrSpan= CurrentlyOnThisPage ? "span" : "a";
}

<@linkOrSpan><text>Tab Content</text></@linkOrSpan>

No errors about closing tags with this.

Looks a bit cleaner too ihmo.

HTH

Upvotes: 4

Related Questions