Asp.Net MVC : Having one form and multiple submit buttons<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

Asp.Net MVC : Having one form and multiple submit buttons

Posted on: August 6, 2014

Imagine the case that you have a form that you Save but that you can Save and Continue. Or a Form that you can Save and Delete. Both in the same form. You wan to be able to do two actions with a single form. This possible scenario can be handled with Asp.Net MVC very easily.

First of all, you do as usual in your Razor by create your form and adding inside it all inputs box.

Second, you add inside the form your two buttons. However, you set a value for your buttons and name that must be the same for all your buttons. Having your button with the same name will trigger the browser to send the one that is active. If you are pressing the first button, the value of this first button is sent.

1<input type="submit" name="action" value="Save" />
2<input type="submit" name="action" value="Save and Continue" />
3<!-- OR -->
4<button type="submit" name="action" value="save">Save</button>
5<button type="submit" name="action" value="saveAndContinue">Save and Continue</button>

Using button over input has the advantage to let you set value that does not change of the localized string that is displayed on the screen.

The third step is on the server side. The controller's action must read the value and do a decision.

1public ActionResult Register(string action, YourViewModel viewModel) {
2 if (button == "save") { }
3 //...

This can be improved by using a constant between the Controller and the View. This way, you do not have string that are different if someone change the name of the button.