ASP.NET MVC and Multiple Submit Buttons–Part 2
Posted by: Malcolm Sheridan
in Category ASP.NET MVC
Abstract: The following article demonstrates how to differentiate multiple submit buttons in the same form with MVC and jQuery.
My last article focused on how to have multiple submit buttons in the same form, and how to differentiate them in your action method. If you missed it you can read it here. If you want to hijack your form and post it via Ajax, you need to do some extra work. Controls that have a name attribute are posted as part of the form because they’re a successful control. However when you use Ajax to post a form, only successful controls are serialized into the string. Submit buttons aren’t serialized seeing as though the form wasn’t submitted using a button. In this example I’ll show you one way of doing this. As always there are plenty of other ways, but this is what I came up with.
For this example I’m using the same form as I used in the first article.
One form, two submit buttons. The PostData action accepts givenName, surname and both submit buttons.
The form will work as expected. Both submit buttons submit the form and only the text box fields are posted. There’s no way to differentiate which button submitted the form. The way to do this is to give the submit buttons a name, but that’s not all you need to do. Remember by default submit buttons aren’t serialized into the string that is posted to the server, so you’ll need to write an object literal and post that instead. Here’s one way to do this. I’ll explain why I’m doing this after.
This is a lot of code to get this to work. Let’s break it down. In Firefox you can find out which element fired the event by querying explicitOriginalTarget. Unfortunately Internet Explorer doesn’t support this, hence why I’m adding a class to the submit button when it's clicked.
The next thing to do is build up an object literal and to find out which submit button was clicked. I'm using jQuery’s hasClass function.
From there you post the form using jQuery’s post function. Now you can identify which button submitted the form. To take this example one step further, you could even decorate your action to only allow requests via an Ajax call. If you'd like to read up on how to do this, you can read an article I wrote a while ago on Restrict ASP.NET MVC Action's Using The ActionMethodSelectorAttribute.
I hope you find this useful. I've had to do this quite a few times during projects. Hopefully you can find a use for it too.
The entire source code of this article can be downloaded over here