How to handle Multiple submit buttons in the same form/page

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.

<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.

[HttpPost]
[MultipleButton(Name = “action”, Arg= “signin”)]
public ActionResult signin()
{
return RedirectToAction(“Index”, “signin”);
}
[HttpPost]
[MultipleButton(Name = “action”, Arg= “Signup”)]
public ActionResult Signup()
{
return RedirectToAction(“Index”, “Signup”);
}
[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.


[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

OUTPUT :

Multiple submit buttons1

Advertisements