How to implement Multiple submit button in single View of asp.net MVC?


Index

Save

We can do this task in so many ways. But one of simple approach to do this using “attribute-based solution”
To achieve this task we can do like this

Step 1: Create one class i.e HttpParamActionAttribute.cs in asp.net MVC application.


using System;
using System.Reflection;
using System.Web.Mvc;
 
namespace MultipleButtonClick
{
    public class HttpParamActionAttribute : ActionNameSelectorAttribute
    {
        public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
        {
            if (actionName.Equals(methodInfo.Name, StringComparison.InvariantCultureIgnoreCase))
                return true;
 
            var request = controllerContext.RequestContext.HttpContext.Request;
            return request[methodInfo.Name] != null;
        }
    }
}

Step 2: Create a Home control and write some action like this

using System.Web.Mvc;
 
namespace MultipleButtonClick.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
 
        public ActionResult Index()
        {
            ViewBag.msg = "I am from Index action.";
            return View();
        }
 
        [HttpPost]
        [HttpParamAction]
        public ActionResult Save()
        {
            ViewBag.msg = "I am from Save action.";
            return View();
        }
 
        [HttpPost]
        [HttpParamAction]
        public ActionResult Delete()
        {
            ViewBag.msg = "I am from Delete action.";
            return View();
        }
    }
}

Step 3:Create one View I.e Index write the html code like this



@{
    ViewBag.Title = "Index";
}
 
<h2>Index</h2>
 
@ViewBag.msg
 
<br /> <br />
@using (@Html.BeginForm())
{
 
    <input type="submit" name="Save" value="Save" />
 
    <input type="submit" name="Delete" value="Delete" />
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: