I have an ASP.NET MVC app with a form. Say this form has an arbitrary number of buttons, each with their own action.
<input type="button" id="action1" value="One" />
<input type="button" id="action2" value="Two" />
... and so forth
We want the user to click on one and have a jQuery action fire to submit the form and then repost the form with new information.
There are several ways to implement this. What is the best practice on how to design this elegantly? Please provide code snippets if you can.
Set up an object literal of potential actions:
Then write a selector that grabs all the buttons (be as specific as you need to be) and attach each function based on the element’s id to the click handler. Using event delegation (‘$.live()’) you can increase performance for the case when there are several buttons, or when buttons are added dynamically.
This would call the related action in the ‘actions’ variable on each click (you should probably validate that the function exists, as well).
Then inside each of the action functions, you can submit to different urls, or ajax submit, or load new information, or do anything you want. As far as ‘repost[ing] the form’ goes, that would be a server-side function that prefilled each input element with its previous value, much like you would do on an invalid submit.
This gives you a single line of code to handle the events, and then a clean structure to build each of your actions in.