In this post, we will discuss how to handle the multiple submit button event in ASP .NET MVC without using javascript. The form could contain more than one submit button issuing a form post to a different controller action. We can achieve this situation by using ActionNameSelectorAttribute.
Implementing View :
<div> <form action="" method="post"> <input type="submit" value="Save" name="action:Save" /> <input type="submit" value="Edit" name="action:Edit" /> </form> </div>
Implement ActionNameSelectorAttribute
Here i am creating a class that inherits from ActionMethodSelectorAttribute. The first parameter is ControllerContext, this parameter will contain the FormValueProvider object. This contains values posted in the form in a NameValueCollection object. Using this parameter we can identify which button clicked/submitted in the form.
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class HandleMultipleSubmitAttribute : ActionNameSelectorAttribute { public string FormKey { get; set; } public string FormName { get; set; } public override bool IsValidName(ControllerContext ctrContext, string actionName, MethodInfo methodInfo) { var isValidEvent = false; var keyValue = string.Format("{0}:{1}", FormKey, FormName); var value = ctrContext.Controller.ValueProvider.GetValue(keyValue); if (value != null) { ctrContext.Controller.ControllerContext.RouteData.Values[FormKey] = FormName; isValidEvent = true; } return isValidEvent; } }Action Method
The next step is to create two action methods, which containing the Save and Edit functionality. To ensure that either of these actions will be invoked, I’m going to decorate them with the HandleMultipleSubmit attribute class.
public class MultipleSubmitController : Controller { [HttpPost] [HandleMultipleSubmit(FormKey = "action", FormName = "Save")] public ActionResult Save() { return null; } [HttpPost] [HandleMultipleSubmit(FormKey = "action", FormName = "Edit")] public ActionResult Edit( ) { return null; } }Execution :
- After Save/Edit button is clicked, the input named Save will be injected into the form and that will be sent in the forms collection. Before executing the action method, attribute will be executed and it will check the values in the FormValueProvider and find the match value specified on the attribute.
- If posted form contains a value that matches the value in HandleMultipleSubmit then IsValidForRequest method will returns true, so then it will start executing the proper action.
Keep Cool Coding…