Articles in categories

Now on Amazon

Multiple submit buttons on form in ASP.NET MVC Framework.

How to handle multiple submit buttons on form in ASP.NET MVC Framework without Javascript or Jquery?

Original post here.

MultipleButtonAttribute class

    [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 = $"{Name}:{Argument}";
            var value = controllerContext.Controller.ValueProvider.GetValue(keyValue);

            if (value != null)
            {
                controllerContext.Controller.ControllerContext.RouteData.Values[Name] = Argument;
                isValidName = true;
            }

            return isValidName;
        }
    }

View

      <input type="submit" value="Edit" name="action:EditClient" class="btn btn-default" style="margin-left: 10px"/>
      <input type="submit" value="Add" name="action:AddClient" class="btn btn-default"/>

Controller:

        [HttpPost]
        [MultipleButton(Name = "action", Argument = "AddClient")]
        public ActionResult AddClient(ClientViewModel model)
        {
            return RedirectToAction("Create");
        }

        [HttpPost]
        [MultipleButton(Name = "action", Argument = "EditClient")]
        public ActionResult EditClient(ClientViewModel model)
        {
            int? clientId = null;
            if (model.SelectedClientId != 0)
            {
                clientId = model.SelectedClientId;
            }

            return RedirectToAction("Create", new { id = clientId });
        }