Search code examples
htmlhref

Use a condition on href tag html


I have the following code :

if (client.id != 0)
{
    var summaryLink = Url.Action("Add", "Client");
    <a href="@summaryLink">
        <div>
            <h3>Client</h3>
        </div>
    </a>
}
else
{
    <a>
        <div class="mdl-tabs__title">
            <h3>Client</h3>
        </div>
    </a>
}

This works, but I don't want to repeat the code inside the tag but add the href on condition.

Any idea of how I can do this?


Solution

  • You could use a ternary operator? see docs also using a hash won't cause a redirect you could use an empty string or some other alternative see

    var summaryLink = client.id != 0 ? Url.Action("Add", "Client") : "#";
    <a href="@summaryLink">
      <div>
        <h3>Client</h3>
      </div>
    </a>