Blazor link - disable href if there's an onclick method

tomRedox picture tomRedox · May 17, 2019 · Viewed 9k times · Source

In Blazor I have an <a> element that has both a href and an onclick method:

<a href="" onclick="@(() => ChangePage(_someObject))">Test</a>

onclick calls this method:

  private bool ChangePage(object objectToDisplay)
  {
    _currentObject = objectToDisplay;
    StateHasChanged();

    return false;
  }

Normally in JavaScript returning false from the event method stops the subsequent navigation to the link in the href but this doesn't seem to be working with my code above.

How can I stop Blazor changing the page to the root url after the link is clicked?

(The obvious answer here would be to remove the href altogether, but I'm using the link in a bootstrap Pill and removing the href stops the Pills working)

Other things I've tried that didn't work:

  • Changing the <a> element to a span and setting the data-target attribute, but that stops the Pills rendering properly.
  • Adding return into the onclick event (as per this answer): onclick="return @(() => ChangePage(_overviewModel))" but that doesn't compile.
  • Adding return after the onclick event: onclick="@(() => ChangePage(_overviewModel)); return false;" but that doesn't compile either.
  • using a Blazor NavLink component <NavLink href="" onclick="@(() => ChangePage(_someObject))">NavLink</NavLink>

Answer

Stilgar picture Stilgar · Jan 6, 2020

The way to do it after release 3.1 of ASP.NET Core seems to be

<a href="" @onclick="@SomeAction" @onclick:preventDefault />