ProgrammerGuide.Net | Step by Step Programmer Guide

Handling Multiple Submit Buttons in Razor View | ASP.NET MVC Framework

Multiple Submit Buttons in ASP.NET MVC can be handled in different ways. Here we will implement a clean attribute-based solution to handle multiple submit buttons in ASP.NET MVC Framework. Below is code snippet of an ASP.NET MVC attribute to handle multiple submit buttons in a Razor form.

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class MultipleSubmitAttribute : ActionNameSelectorAttribute
{
    public string Name { get; set; }
    public string Argument { get; set; }

    public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
    {
        bool isValidName = false;
        string keyValue = string.Format("{0}:{1}", Name, Argument);
        var value = controllerContext.Controller.ValueProvider.GetValue(keyValue);
        if (value != null)
        {
            controllerContext.Controller.ControllerContext.RouteData.Values[Name] = Argument;
            isValidName = true;
        }

        return isValidName;
    }
}

Now, let’s make use of the MultipleSubmitAttribute in our actions in a controller that gets called to the appropriate submits. We have two MVC actions Send & Save. Each action will be called when the appropriate button is clicked by the user. Below is the code snippet of actions decorated with MultipleSubmitAttribute.

[HttpPost]
[MultipleSubmit(Name = "action", Argument = "Send")]
public ActionResult Send(Model model) 
{ 
...
}

[HttpPost]
[MultipleSubmit (Name = "action", Argument = "Save")]
public ActionResult Save(Model model) 
{ 
...
}

Below is a snippet of razor view having a simple form with multiple submit buttons:

<form action="" method="post">
 <input type="submit" value="Save" name="action:Save" />
 <input type="submit" value="Send" name="action:Send" />
</form>
Please click here for related products on Amazon!

Jayashee

Add comment

Want to Check Celebrities News?