Handle Multiple submit buttons in single page
Scenario :
For example, we have a login form with “sign in”,”sign up” and “cancel” button. In this scenario, “sign in” will redirect/do some action,same like sign up and cancel. Lets we discuss how to handle multiple button in same form (calling different action method).
View :
Let we create view with three submit button.
1 2 3 4 5 |
<form action="" method="post"> <input type="submit" value="signin" name="action:signin" /> <input type="submit" value="Signup" name="action:Signup" /> <input type="submit" value="Cancel" name="action:Cancel" /> </form> |
Controller
Here i am going to create three separate action method for signin,signup,cancel for capture the click event in the controller.
1 2 3 4 5 6 |
[fusion_builder_container hundred_percent="yes" overflow="visible"][fusion_builder_row][fusion_builder_column type="1_1" background_position="left top" background_color="" border_size="" border_color="" border_style="solid" spacing="yes" background_image="" background_repeat="no-repeat" padding="" margin_top="0px" margin_bottom="0px" class="" id="" animation_type="" animation_speed="0.3" animation_direction="left" hide_on_mobile="no" center_content="no" min_height="none"][HttpPost] [MultipleButton(Name = "action", Arg= "signin")] public ActionResult signin() { return RedirectToAction("Index", "signin"); } |
1 2 3 4 5 6 |
[HttpPost] [MultipleButton(Name = "action", Arg= "Signup")] public ActionResult Signup() { return RedirectToAction("Index", "Signup"); } |
1 2 3 4 5 6 |
[HttpPost] [MultipleButton(Name = "action", Arg= "Cancel")] public ActionResult Cancel() { return RedirectToAction("Index", "Home"); } |
Custom ActionNameSelectorAttribute :
Here we going to implement a custom ActionMethodSelectorAttribute to check which button submitted the form.This contains values posted in the form in a NameValueCollection object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class MultipleButtonAttribute : ActionNameSelectorAttribute { public string Name{get;set;} public string Arg{get;set;} public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo) { bool isValidName = false; string keyValue = string.Format("{0}:{1}", Name, Arg); var value = controllerContext.Controller.ValueProvider.GetValue(keyValue); if (value != null) { controllerContext.Controller.ControllerContext.RouteData.Values[Name] = value; isValidName = true; } return isValidName; } } |
Note : While clicking the button, MultipleButtonAttribute method will execute first to know which action Mthod to call