Multiple Submit button in Asp.Net MVC
In this article, we will be discussing various ways of handling Submit button in asp.Net MVC.
Below are the different ways
- Multiple Forms
- JQuery
- Action Name Selector Attribute
Now let’s elaborate one by one.
Multiple Forms
With this approach, we can create multiple forms and each form will have different methods in the action attribute of form as shown below,
- @ {
- ViewBag.Title = "Home Page";
- } < form action = "Home"
- method = "post" > < input type = "submit"
- value = "Add"
- name = "Add" / > < /form> < form action = "Home"
- method = "post" > < input type = "submit"
- value = "Remove"
- name = "Remove" / > < /form>
Now in the above example we have create two separate forms. First form is calling Add and second form is calling Remove.
JQuery
With this approach, we can use jQuery post methods for each call as shown below,
- <script src="~/Scripts/jquery-1.10.2.js"></script>
- <script>
- function Add() {
- $.post("Add", null, Fun1);
- }
-
- function Remove() {
- $.post("Remove", null, Fun1);
- }
-
- function Fun1(data) {
- alert(data);
- }
- </script> <input type="submit" value="Add" name="Add" onclick="Add()" /> <input type="submit" value="Remove" name="Remove" onclick="Remove()" />
Now in the above example we have created Add() and Remove() which is calling Fun1(). Fun1() is showing received data in alert message. However Onlcick of Add submit button we are calling Add() and Remove submit button is calling Rmove().
Action Name Selector Attribute
ActionNameSelectorAttribute is an attribute which that affects the selection of an action method.
In this we need to implement IsValidName by inheriting ActionNameSelectorAttribute as shown below,
- public class AddRemoveButton: ActionNameSelectorAttribute {
- public string Name {
- get;
- set;
- }
- public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo) {
- var value = controllerContext.Controller.ValueProvider.GetValue(Name);
- if (value == null) return false;
- return true;
- }
- }
Now in the above example, we have created property Name. And overridden IsValidName().
We are validating values of Valueprovider with the Name property. If the value is null then we are returning false else we are returning true.
Now we have to call AddRemoveButton on action methods as shown below,
- public class HomeController: Controller {
- [AddRemoveButton(Name = "Add")]
- public ActionResult Add() {
- return Content("Add clicked");
- }
- [AddRemoveButton(Name = "Remove")]
- public ActionResult Remove() {
- return Content("Remove clicked");
- }
- }
Now in the above example we have added AddRemoveButton by paasing name of actionmethods in name property.