Home > DeveloperSection > Forums > Handling Multiple submit button in asp.net mvc?
Pravesh Singh

Total Post:411

Points:2881
Posted on    November-18-2014 3:02 AM

 ASP.NET MVC C#  ASP.Net  HTML  Handler 
Ratings:


 1 Reply(s)
 710  View(s)
Rate this:

Is there some easy way to handle multiple submit buttons from the same form? Example:

<% Html.BeginForm("MyAction", "MyController", FormMethod.Post); %>

<input type="submit" value="Send" />

<input type="submit" value="Cancel" />

<% Html.EndForm(); %>

Any idea how to do this in ASP.NET Framework Beta? All examples I've googled for have single buttons in them.



Royce Roy
Royce Roy

Total Post:134

Points:938
Posted on    November-18-2014 6:06 AM

Here is a mostly clean attribute-based solution to the multiple submit button issue based heavily on the post and comments from Maartin Balliauw.

[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;

    }

}

razor:

<form action="" method="post">

 <input type="submit" value="Save" name="action:Save" />

 <input type="submit" value="Cancel" name="action:Cancel" />

</form>

and controller:

[HttpPost]

[MultipleButton(Name = "action", Argument = "Save")]

public ActionResult Save(MessageModel mm) { ... }

[HttpPost]

[MultipleButton(Name = "action", Argument = "Cancel")]

public ActionResult Cancel(MessageModel mm) { ... }


Don't want to miss updates? Please click the below button!

Follow MindStick