ASP.NET MVC Tip #4 - Handling Multiple Form Actions on One View
Scenario:
You have a view which renders a list of customers. You need to provide a way to delete customers from this table view of the data. In your "CustomersController" you have a Delete action which takes a Customer ID. How do we go about providing the user with a simple interface where multiple actions can be posted from one view?
Solution:
There's basically two approaches we can take to solve this. One is to use javascript to get the ID of the customer from the DOM, handle the "onclick" event and submit the form to a "javascript generated" action. The other option is to render multiple forms on the view. For this exercise, we'll concentrate on the latter technique.
In a typical web forms based ASP.NET application, we're used to having one form per page. In the MVC framework, we're in ful control of the HTML rendered which means we can have more than one form on the page. This means that each form can post to a different action. Assume we have a collection of Smurfs which will be rendered on a view. This ViewPage will use a strongly typed ViewData with the list of Smurfs. As we're rendering the view, we simply need to set the parameters of the form accordingly.
At this point, we simply handle the controller action as any other form. The actual HTML output looks like this. Notice how the action uses the item.ID.

We'll explore the technique with JavaScript in a later post. Hope this helps!