How to separate Action method for each submit button

1 minute read


When creating the input form, there were multiple submit buttons, so a memo when creating that process.
This time, I created a selector attribute and set that attribute in the action method.


C# 7.3


I referred to the following page this time.


Create MultipleButtonAttribute class in Models folder.

MultipleButtonAttribute class

using System;
using System.Web;
using System.Web.Mvc;
using System.Reflection;

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

        public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
            var isValidName = false;
            var 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;


@using (Html.BeginForm())
    	<input type="submit" name="action:Cancel" value="Cancel">
    	<input type="submit" name="action:Save" value="Save">


//For view display
public ActionResult Input(InputContents input)
    ViewBag.SelectOptions = new SelectListItem[]
        new SelectListItem(){Value="1",Text="text1"},
        new SelectListItem(){Value="2",Text="text2"},
        new SelectListItem(){Value="3",Text="text3"}

    return View(input);
//Called when the cancel button is pressed
[MultipleButton(Name = "action", Argument = "Cancel")]
public ActionResult Cancel(InputContents input)
    return View("Input", input);
//Called when the save button is pressed
[MultipleButton(Name = "action", Argument = "Save")]
public ActionResult Save(InputContents input)
    return View("Input", input);

The controller has an action method to receive the above submit, Cancel, Save, and an action method to display a view called Input.


It’s different from the purpose of this article, but in ASP.NET, when returning a View with an action method, if you do not specify the action method, you will get stuck without searching for a cshtml file with the same name as the action method. It’s gone. The content of this article is almost the same as the referenced page, but the action method to be returned to View is explicitly specified.