有一些简单的方法可以处理来自同一表单的多个提交按钮吗?例如:
<% Html.BeginForm("MyAction", "MyController", FormMethod.Post); %> <input type="submit" value="Send" /> <input type="submit" value="Cancel" /> <% Html.EndForm(); %>
任何想法如何在ASP.NET Framework Beta中做到这一点?我搜索过的所有示例中都包含一个按钮。
在很大程度上基于MaartenBalliauw的帖子和评论,这是一个针对多个提交按钮问题的基于属性的,几乎干净的解决方案。
[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) { ... }