How do you handle multiple submit buttons in ASP.NET MVC Framework?

后端 未结 30 3006
一个人的身影
一个人的身影 2020-11-21 07:16

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

<% Html.BeginForm(\"MyAction\", \"MyController\", FormMethod.Pos         


        
30条回答
  •  孤街浪徒
    2020-11-21 07:46

    Just written a post about that: Multiple submit buttons with ASP.NET MVC:

    Basically, instead of using ActionMethodSelectorAttribute, I am using ActionNameSelectorAttribute, which allows me to pretend the action name is whatever I want it to be. Fortunately, ActionNameSelectorAttribute does not just make me specify action name, instead I can choose whether the current action matches request.

    So there is my class (btw I am not too fond of the name):

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

    To use just define a form like this:

    <% using (Html.BeginForm("Action", "Post")) { %>
      
      
      
    <% } %> 
    

    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.

提交回复
热议问题