Using an anchor tag helper, how can we open an ASP.NET Core MVC View
in a new browser window-tab. I tried the following but first it complained that target
attribute need to have href
attribute as well. But, as we know, we can't use the href attribute with asp-action
attribute in MVC Core
; otherwise we get the error shown below. NOTE: I've seen some suggestions like this one, but they are not tag helper related:
<a asp-action="testAction" href="#" target="_blank">Click Here</a>
Error:
InvalidOperationException: Cannot override the 'href' attribute for . An with a specified 'href' must not have attributes starting with 'asp-route-' or an 'asp-action', 'asp-controller', 'asp-area', 'asp-route', 'asp-protocol', 'asp-host', or 'asp-fragment' attribute.
Unlike HtmlHelpers, a tag helper is a class that attaches itself to an HTML-compliant element in a View or Razor Page. The tag helper can, through its properties, add additional attributes to the element that a developer can use to customize the tag's behavior.
The Anchor Tag Helper enhances the standard HTML anchor ( <a ... > </a> ) tag by adding new attributes. By convention, the attribute names are prefixed with asp- . The rendered anchor element's href attribute value is determined by the values of the asp- attributes.
The opt-out character (“!”) is used to disable the Tag Helper at the element level. With the opt-out character, the HTML will not be generated for the label tag in the above case. We can use this opt-out character if we want to conditionally control rendering of the HTML elements.
I’m not sure if you’re asking a question or if you’re sharing your findings?
As @Mohamed Rozza mentioned in the comments, if you disregard the Visual Studio warning about the target
attribute only allowed when the href
is present, then you’ll quickly realize that the hyperlink actually works and opens in a new tab. Regardless of Visual Studio complaining.
As you’ve also pointed out, there is an alternative/workaround where you could create your link like this:
<a href="@Url.Action("testAction","Home")" target="_blank">Click Here</a>
But, as you’ve said, this approach is not tag helper related. But so what?
My questions are these:
You have two working example that achieves your task.
None of these two approaches are bad/wrong. If for some reason you feel compelled to write your own custom tag helper to overcome this...then by all means, go ahead!
If you wish to report a bug to Microsoft about the tag helper not supporting the target attribute without the href, then by all means go ahead!
And finally, if I do not understand the need to be 100% tag helper related (or if I’m over simplifying stuff) then by all means, feel free to share as we may offer a better alternative.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With