Friday 28 December 2018

How to handle multiple submit button in MVC

There are 3 steps to follow for this:

Step1: Create a class in your application:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;

namespace PocA2019.Attributes
{
    [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;
        }
    }
}

Step2: Add 2 method save and cancel
using System.Web.Mvc;

namespace PocA2019.Controllers
{
    public class HomeController : Controller
    {
     
        [HttpPost]
        [MultipleButton(Name = "action", Argument = "Save")]
        public ActionResult Save(MessageModel mm)
        {
            return RedirectToAction("Index");
            //...
        }

        [HttpPost]
        [MultipleButton(Name = "action", Argument = "Cancel")]
        public ActionResult Cancel(MessageModel mm)
        {
            return RedirectToAction("Index");
            // ...
        }
    }
}

Step3 : Add your html form control:
 <form action="" method="post">
        <input type="submit" value="Save" name="action:Save" />
        <input type="submit" value="Cancel" name="action:Cancel" />
    </form>

Now run the application and click on Save and Cancel button. you will as expected behaviour.

Thanks for reading this article............