ASPNET MVC: Handling Multiple Buttons on a Form with jQuery

Sometimes your task in MVC involves many buttons in the same form. Such as the screen shot here.

What happens in most situations is that you end up having some code that kind of looks like this:


<form action="/foo/save">

<!-- My HTML and multiple buttons -->

</form>

… and then the code looks like this


public ActionResult Save(CustomerList customers, string buttonName)

{

if(buttonName == "Save")

{

// do something

}

else if (buttonName == "Reload")

{

// etc, etc

}
// Other if's, etc, etc

}

We can solve this with a little jQuery. By attaching a click handler to the button we can tell the form where we want it to go. Therefore keeping our controllers actions very slim.

Here’s the jQuery:


// This assumes your buttons have id's "save-button" and "update-button"

$("#save-button").click(function () {

 // Redirect to add facility for Credit Exposure
 var form = $(this).parents('form:first');
 form.attr('action', '<%=Url.RouteUrl(new { controller = "foo", action = "save"  }) %>');
});

$("#reload-button").click(function () {

 // Redirect to add facility for Credit Exposure
 var form = $(this).parents('form:first');
 form.attr('action', '<%=Url.RouteUrl(new { controller = "foo", action = "reload"  }) %>');
});

Now when the user clicks “Save” they will go to the “Save” Action on the “FooController”. When the user clicks “Reload” they will go to the “Reload” action on the”FooController”. No more logic switches in the Controller.

You can download and example here (minus the MVC Goo):

Android Dev Digest

Get the best Android Developer posts delivered weekly to your inbox.

Don't worry, I wont spam (I hate that stuff too).