1) Dirty one
<input type="submit" id="Submit1" name="btnSubmit", value="action:First" />
<input type="submit" id="Submit2" name="btnSubmit", value="action:Second" />
[HttpPost]
public ActionResult MyAction(string btnSubmit, MyFormModel model)
{
switch (btnSubmit) {
case "action:First":
break;
case "action:Second":
break;
}
2) Nicer - refactor code above to attribute
Like idea from
http://blog.maartenballiauw.be/post/2009/11/26/Supporting-multiple-submit-buttons-on-an-ASPNET-MVC-view.aspx[
^]
Rephrasing code in article above:
[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)
{
bool isValidName = false;
string 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;
}
}
and your code
[HttpPost]
[MultipleButton(Name = "action", Argument = "First")]
public ActionResult First(MyFormModel model) { ... }
[HttpPost]
[MultipleButton(Name = "action", Argument = "Second")]
public ActionResult Second(MyFormModel model) { ... }