serge
serge

Reputation: 15239

Make tag helper work "button" like "a"

In ASP.NET Core I can set an action to a link item a, however if I change it to a button it doesn't work anymore.

What is the correct way to bind an action/controller to a button click?

<a asp-action="Delete" asp-route-id="@item.Id">remove</a> @*work*@

vs

<button asp-action="Delete" asp-route-id="@item.Id">remove</button> @*does not work*@

Upvotes: 3

Views: 7987

Answers (1)

Camilo Terevinto
Camilo Terevinto

Reputation: 32063

It's not that it does not work, they are different Tag Helpers with different usage:
If you hover over the <a> you will see it implements AnchorTagHelper, while the <button> implements the FormActionTagHelper, because it is supposed to be used in <form>s.

So, in order to get the same behavior, you would do this:

<a asp-action="Index">aaaa</a>

<form>
    <button asp-action="Index">bbbbb</button>
</form>

Note, though, that the button is rendered as formaction="/", not as href="/", and this is why you need to wrap it inside a form. The second could also be written like this:

<form asp-action="Index">
    <button type="submit">bbbbb</button>
</form>

Upvotes: 6

Related Questions