Recently I came across a use case of a form which needed two submit buttons. One submit button would just save the data for further edition. Second submit button would save the data and lock it, so you wouldn’t be able to edit it anymore. The best way I know to solve this task is to use formaction attribute. It’s not really a “secret” (as in headline) but it’s lesser known. There is only a one use case for it, but when you need it then there is probably no better way.

What is the formaction attribute

Formaction allows us to define a uri inside a button. It will be used instead of form action uri. This gives us ability to define as many buttons as we need and each of button can point to different url.

The usual way of creating a form submit button

We all know it, there is no need for explanation. So here it is, a basic form with a single submit button.

1
2
3
<form action="/save">
    <button type="submit">Save</button>
</form>

Formaction example

In this example I’ve added a second button which points to different url. In this case it contains additional query parameter, but you can use whatever url you want to.

Note that the first button still points to form/action url (which is /save).

1
2
3
4
<form action="/save">
    <button type="submit">Save</button>
    <button formaction="/save?lock=true" type="submit">Save&Lock</button>
</form>

FormActionTagHelper for .NET Core MVC

If you are using .NET Core MVC then you should know that it already comes with FormActionTagHelper which “extends” button tag with extra functionality. By using it we can create formaction url the same way we create link url.

We’re pointing to an action with asp-action attribute and we’re adding a lock query parameter with asp-route-lock.

1
2
3
4
<form asp-action="save">
    <button type="submit">Save</button>
    <button asp-action="save" asp-route-lock="true" type="submit">Save&Lock</button>
</form>

It will produce the same HTML as the earlier example. The difference here is that the framework automatically generates resource uri.

Also this tag helper works for input and button elements with type set to image or submit.