ASP.Net MVC & Multiple Submit Button

ASP.Net MVC & Multiple Submit Button

While developing any web applications we use to design lot more forms. Most of the times a form perform a single action, posting data to some controller. There is no necessity that each of the form will contain only a single submit button. Sometimes, we may need a form which will contain multiple submit buttons.  As in the following case

So in this case, our form will be posting data to a single action Post but it contains 2 different submit button.  So to handle this scenario, we need to code something like this in our controller.

Also this looks very simple when we have a simple Action, think how about doing this on a form of 10 fields & 4 buttons.

How if I am able to specify the name of the button near the action method wherein I will specify the name of the button on which that action needs to be invoked.  We can achieve this in Asp.Net MVC by using the ActionMethodSelectorAttribute attribute. Here is a code snippet to show the use of the attribute

The ActionMethodSelectorAttribute is executed before the Action is executed, so we here we can check which button is clicked while submitting the form using the Form NameValueCollection object on the IsValidForRequest event of the ActionMethodSelectorAttribute.

Here is the implementation code for the class.

This attribute will also help preventing the JavaScript attacks as this will only accept the values submitted by the specific submit button.

You can download the source code here.