ASP.NET MVC Core/6: Multiple submit buttons
Solution 1
You can use the HTML5 formaction
attribute for this, instead of routing it server-side.
<form action="" method="post">
<input type="submit" value="Option 1" formaction="DoWorkOne" />
<input type="submit" value="Option 2" formaction="DoWorkTwo"/>
</form>
Then simply have controller actions like this:
[HttpPost]
public IActionResult DoWorkOne(TheModel model) { ... }
[HttpPost]
public IActionResult DoWorkTwo(TheModel model) { ... }
A good polyfill for older browsers can be found here.
Keep in mind that...
- The first submit button will always be chosen when the user presses the carriage return.
- If an error -
ModelState
or otherwise - occurs on the action that was posted too, it will need to send the user back to the correct view. (This is not an issue if you are posting through AJAX, though.)
Solution 2
ASP.NET Core 1.1.0 has the FormActionTagHelper
that creates a formaction
attribute.
<form>
<button asp-action="Login" asp-controller="Account">log in</button>
<button asp-action="Register" asp-controller="Account">sign up</button>
</form>
That renders like this:
<button formaction="/Account/Login">log in</button>
<button formaction="/Account/Register">sign up</button>
It also works with input
tags that are type="image"
or type="submit"
.
Solution 3
I have done this before and in the past I would have posted the form to different controller actions. The problem is, on a server side validation error you are either stuck with:
-
return View(vm)
leaves the post action name in the url… yuck. -
return Redirect(...)
requires usingTempData
to save theModelState
. Also yuck.
Here is what I chose to do.
- Use the
name
of the button to bind to a variable on POST. - The button
value
is an enum to distinguish the submit actions. Enum is type safe and works better in a switch statement. ;) - POST to the same action name as the GET. That way you don't get the POST action name in your URL on a server side validation error.
- If there is a validation error, rebuild your view model and
return View(viewModel)
, following the proper PGR pattern.
Using this technique, there is no need to use TempData
!
In my use case, I have a User/Details page with an "Add Role" and "Remove Role" action.
Here are the buttons. They can be button instead of input tags... ;)
<button type="submit" class="btn btn-primary" name="SubmitAction" value="@UserDetailsSubmitAction.RemoveRole">Remove Role</button>
<button type="submit" class="btn btn-primary" name="SubmitAction" value="@UserDetailsSubmitAction.AddRole">Add Users to Role</button>
Here is the controller action. I refactored out the switch code blocks to their own functions to make them easier to read. I have to post to 2 different view models, so one will not be populated, but the model binder does not care!
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Details(
SelectedUserRoleViewModel removeRoleViewModel,
SelectedRoleViewModel addRoleViewModel,
UserDetailsSubmitAction submitAction)
{
switch (submitAction)
{
case UserDetailsSubmitAction.AddRole:
{
return await AddRole(addRoleViewModel);
}
case UserDetailsSubmitAction.RemoveRole:
{
return await RemoveRole(removeRoleViewModel);
}
default:
throw new ArgumentOutOfRangeException(nameof(submitAction), submitAction, null);
}
}
private async Task<IActionResult> RemoveRole(SelectedUserRoleViewModel removeRoleViewModel)
{
if (!ModelState.IsValid)
{
var viewModel = await _userService.GetDetailsViewModel(removeRoleViewModel.UserId);
return View(viewModel);
}
await _userRoleService.Remove(removeRoleViewModel.SelectedUserRoleId);
return Redirect(Request.Headers["Referer"].ToString());
}
private async Task<IActionResult> AddRole(SelectedRoleViewModel addRoleViewModel)
{
if (!ModelState.IsValid)
{
var viewModel = await _userService.GetDetailsViewModel(addRoleViewModel.UserId);
return View(viewModel);
}
await _userRoleService.Add(addRoleViewModel);
return Redirect(Request.Headers["Referer"].ToString());
}
As an alternative, you could post the form using AJAX.
Solution 4
An even better answer is to use jQuery Unobtrusive AJAX and forget about all the mess.
- You can give your controller actions semantic names.
- You don't have to redirect or use tempdata.
- You don't have the post action name in the URL on server side validation errors.
- On server side validation errors, you can return a form or simply the error message.
noox
Programming for 27 years now. Started a community website 1998 with Perl, later PHP/MySQL. At work .NET but very heavy on SQL-Server. So I've been a bit outdated regarding the newest .NET developments lately. Currently I'm digging into .NET vNext/5/Core 1 and EF7. When not in front of the computer then on the mountain bike or freeride skis.
Updated on August 28, 2020Comments
-
noox over 3 years
I need multiple submit buttons to perform different actions in the controller.
I saw an elegant solution here: How do you handle multiple submit buttons in ASP.NET MVC Framework? With this solution, action methods can be decorated with a custom attribute. When the routes are processed a method of this custom attribute checks if the attribute's property matches the name of the clicked submit button.
But in MVC Core (RC2 nightly build) I have not found
ActionNameSelectorAttribute
(I also searched the Github repository). I found a similar solution which usesActionMethodSelectorAttribute
(http://www.dotnetcurry.com/aspnet-mvc/724/handle-multiple-submit-buttons-aspnet-mvc-action-methods).ActionMethodSelectorAttribute
is available but the methodIsValidForRequest
has a different signature. There is a parameter of typeRouteContext
. But I could not find the post data there. So I have nothing to compare with my custom attribute property.Is there a similar elegant solution available in MVC Core like the ones in previous MVC versions?
-
Vlince about 8 yearsWhat might work, depending on if you like this or not, would be to change the actual URL of the <form> element using client side (aka: JQuery). On click even, figure out which button is clicked, changed the [action] attribute of the <form> element and submit() the <form>.
-
-
noox about 8 yearsPerfect! Seems like I have to look into HTML5 in more detail. Strange is: I had the form on the Index-Action. So:
/AreaName/ControllerName
. After clicking the button I got:/AreaName/ButtonFormActionName
. controller part got lost. When I start from/AreaName/ControllerName/ActionName
it works. -
Will Ray about 8 yearsAhh, good catch! You will need to use the
Url.Action(actionName, controllerName)
helper method to generate the proper target for theformaction
attribute in that case. -
noox about 8 yearsThanks for the hint. Works now also on the Index action!
-
Mohammad Akbari about 8 yearsperfect solution, but one pitfal, if we use your way, and irst action is /post/add ,the second one is /post/addcontinue . if user clicks on addcontinue button and the page has validation problema, so we send back the user the form and asks him to correct the errors. but since we return addcontinue action, page url changes to /post/addcontinue , so if user refreshes the page ,the browser makes a get request to /post/addcontinue , and we done have any get action for post/addcontinue. what is the best solution to keep the page url consistent with /post/add in both buttons.
-
Will Ray about 8 years@MohammadAkbari this is a problem inherent to having multiple submit buttons, and unfortunately also occurred with the previous answer for MVC4 and 5. There are a couple of different ways you could achieve what you are looking for, but it depends on the use case. AJAX form submissions would be one option, for example.
-
nologo almost 7 yearshey shuan, one thing i noticed about this is if i validate the model and its incorrect the url changes to the action name. any idea how to address this? something like: { ModelState.AddModelError(string.Empty, "we have an issue here with data in the form"); } return View("Edit", editModel);
-
Damitha almost 7 yearsYou can use one action and switch multiple posts easily by adding a string parameter named "submit" or same as the name of the button to the post action. Check this binaryintellect.net/articles/…
-
Peter Suwara almost 6 yearsThis works in ASP.NET Core 2.0 MVC. It makes using multiple form sections so much easier. It also simplifies hidden fields for ModelView data used between calls. Well done. I had no idea the formaction field for buttons existed. I was having a problem where model fields in forms for different part of the model were cleared as only single form data is retained between posts.
-
Gone Coding over 2 yearsI found this no longer works in ASP for .Net 6. Worked in 5 then stopped when I upgraded the project. Only get a null passed for the named parameter.
-
Jess about 2 yearsMaybe the answer @nologo is to just Redirect? I'm not sure.
-
Jess about 2 yearsHi @GoneCoding, it is working for me in .NET 6.
-
Jess about 2 yearsI was using this technique again in .NET 6. One issue I ran into is that you have to not use a hidden input for the button value you are posting. The ModelState will get in your way.