There are some scenarios where there are multiple buttons on a form, and you need to carry out different logic / validation according to which button was clicked. For example, look at the form sample below.
Clicking the upload button should just deal with the file upload logic, whereas clicking ‘Next’ should perform the main validation for the form etc. Working with webforms there are a couple of ways to implement this – Validation groups on validator controls, and specific click handlers for the buttons on a code-behind page.
Working with the MVC framework, there are two main options – either submitting the form to two different end-points, or having a single endpoint to handle the post with conditional logic.
Providing two separate action methods is nice and clean, but means the browser will end up pointing to a new address after completing the post. Not ideal.
You can implement a single action method running from the same address as the main GET request handler by using the AccectVerbs attribute on the action method. E.g.
1: [ActionName("Index"), AcceptVerbs(HttpVerbs.Get)]
2: public ActionResult FormGet()
3: {
4: // blah
5: }
6:
7: [ActionName("Index"), AcceptVerbs(HttpVerbs.Post)]
8: public ActionResult FormSubmit(byte[] photo, string title, string description)
9: {
10: // blah
11: }
If you need to know which button was clicked, and perform appropriate logic, start by defining a named input control that will submit the form. This could be <input type=”submit”>, <input type=”image”>, or <button>. When one of these controls is used to submit a form, the form data will include the name of the control as both the key and value.
On the signature for your action method, provide a string parameter matching the name of the input control. If the button was clicked, the parameter value will be the name of the form control, otherwise the value will be null.
This will allow you to provide a single endpoint that implements different logic according to which button was clicked.