Thanks to
http://blog.ashmind.com/2010/03/15/multiple-submit-buttons-with-asp-net-mvc-final-solution/
http://weblogs.asp.net/dfindley/archive/2009/05/31/asp-net-mvc-multiple-buttons-in-the-same-form.aspx
public class HttpParamActionAttribute : ActionNameSelectorAttribute { public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo) { if (actionName.Equals(methodInfo.Name, StringComparison.InvariantCultureIgnoreCase)) return true; if (!actionName.Equals("Action", StringComparison.InvariantCultureIgnoreCase)) return false; var request = controllerContext.RequestContext.HttpContext.Request; return request[methodInfo.Name] != null; } }
How to use it? Just have a form similar to this:
<% using (Html.BeginForm("Action", "Post")) { %> <!— …form fields… --> <input type="submit" name="saveDraft" value="Save Draft" /> <input type="submit" name="publish" value="Publish" /> <% } %>
and controller with two methods
public class PostController : Controller { [HttpParamAction] [AcceptVerbs(HttpVerbs.Post)] public ActionResult SaveDraft(…) { //… } [HttpParamAction] [AcceptVerbs(HttpVerbs.Post)] public ActionResult Publish(…) { //… } }
As you see, the attribute does not require you to specify anything at all. Also, name of the buttons are translated directly to the method names. Additionally (I haven’t tried that) these should work as normal actions as well, so you can post to any of them directly.
No comments:
Post a Comment