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

 ̄綄美尐妖づ 提交于 2020-04-12 16:57:25

问题


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>

回答1:


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

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



回答2:


Currently you can't control event propagation in Blazor. This feature will be available in the next preview, which is preview 6. You can see the relevant issue on GitHub, https://github.com/aspnet/AspNetCore/issues/5545.

As you have found the pills in bootstrap are styled based on the elements used hence why swapping the a tag for another breaks things.

I think your options right now are either wait for preview 6 or rewrite the pills yourself.




回答3:


You could try adding the javascript void method to the href.

<a href="javascript: void(0);" onclick="@(() => ChangePage(_someObject))">Test</a>




回答4:


This has been finally fixed.

<a style="text-underline-position:below; cursor:pointer" @onclick="(() => CloseValidation())">x</a>


来源:https://stackoverflow.com/questions/56183721/blazor-link-disable-href-if-theres-an-onclick-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!