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.
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.