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

后端 未结 30 2983
一个人的身影
一个人的身影 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:27

    I've tried to make a synthesis of all solutions and created a [ButtenHandler] attribute that makes it easy to handle multiple buttons on a form.

    I've described it on CodeProject Multiple parameterized (localizable) form buttons in ASP.NET MVC.

    To handle the simple case of this button:

    <button type="submit" name="AddDepartment">Add Department</button>
    

    You'll have something like the following action method:

    [ButtonHandler()]
    public ActionResult AddDepartment(Company model)
    {
        model.Departments.Add(new Department());
        return View(model);
    }
    

    Notice how the name of the button matches the name of the action method. The article also describes how to have buttons with values and buttons with indexes.

    0 讨论(0)
  • 2020-11-21 07:27

    this is the best way that i have found:

    http://iwayneo.blogspot.co.uk/2013/10/aspnet-mvc-action-selector-with-list.html

    Here is the code:

        /// <summary>
        /// ActionMethodSelector to enable submit buttons to execute specific action methods.
        /// </summary>
        public class AcceptParameterAttribute : ActionMethodSelectorAttribute
       {
            /// <summary>
            /// Gets or sets the value to use to inject the index into
            /// </summary>
           public string TargetArgument { get; set; }
    
           /// <summary>
           /// Gets or sets the value to use in submit button to identify which method to select. This must be unique in each controller.
           /// </summary>
           public string Action { get; set; }
    
           /// <summary>
           /// Gets or sets the regular expression to match the action.
           /// </summary>
           public string ActionRegex { get; set; }
    
           /// <summary>
           /// Determines whether the action method selection is valid for the specified controller context.
           /// </summary>
           /// <param name="controllerContext">The controller context.</param>
           /// <param name="methodInfo">Information about the action method.</param>
           /// <returns>true if the action method selection is valid for the specified controller context; otherwise, false.</returns>
           public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
           {
    
               if (controllerContext == null)
               {
                   throw new ArgumentNullException("controllerContext");
               }
    
               Func<NameValueCollection> formGetter;
               Func<NameValueCollection> queryStringGetter;
    
               ValidationUtility.GetUnvalidatedCollections(HttpContext.Current, out formGetter, out queryStringGetter);
    
               var form = formGetter();
               var queryString = queryStringGetter();
    
               var req = form.AllKeys.Any() ? form : queryString;
    
               if (!string.IsNullOrEmpty(this.ActionRegex))
               {
                   foreach (var key in req.AllKeys.Where(k => k.StartsWith(Action, true, System.Threading.Thread.CurrentThread.CurrentCulture)))
                   {
                       if (key.Contains(":"))
                       {
                           if (key.Split(':').Count() == this.ActionRegex.Split(':').Count())
                           {
                               bool match = false;
                               for (int i = 0; i < key.Split(':').Count(); i++)
                               {
                                   if (Regex.IsMatch(key.Split(':')[0], this.ActionRegex.Split(':')[0]))
                                   {
                                       match = true;
                                   }
                                   else
                                   {
                                       match = false;
                                       break;
                                   }
                               }
    
                               if (match)
                               {
                                   return !string.IsNullOrEmpty(req[key]);
                               }
                           }
                       }
                       else
                       {
                           if (Regex.IsMatch(key, this.Action + this.ActionRegex))
                           {
                               return !string.IsNullOrEmpty(req[key]);
                           }
                       }
    
                   }
                   return false;
               }
               else
               {
                   return req.AllKeys.Contains(this.Action);
               }
           }
       }
    

    Enjoy a code-smell-less multi submit button future.

    thank you

    0 讨论(0)
  • 2020-11-21 07:28

    This script allows to specify a data-form-action attribute which will work as the HTML5 formaction attribute in all browsers (in an unobtrusive way):

    $(document).on('click', '[type="submit"][data-form-action]', function(event) {
        var $this = $(this),
        var formAction = $this.attr('data-form-action'),
        $form = $($this.closest('form'));
        $form.attr('action', formAction);             
    });
    

    The form containing the button will be posted to the URL specified in the data-form-action attribute:

    <button type="submit" data-form-action="different/url">Submit</button>   
    

    This requires jQuery 1.7. For previous versions you should use live() instead of on().

    0 讨论(0)
  • 2020-11-21 07:29

    Modified version of HttpParamActionAttribute method but with a bug fix for not causing an error on expired/invalid session postbacks. To see if this is a problem with your current site, open the your form in a window and just before you go to click Save or Publish, open a duplicate window, and logout. Now go back to your first window and try to submit your form using either button. For me I got an error so this change solves that problem for me. I omit a bunch of stuff for the sake of brevity but you should get the idea. The key parts are the inclusion of ActionName on the attribute and making sure the name passed in is the name of the View that shows the form

    Attribute Class

    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class HttpParamActionAttribute : ActionNameSelectorAttribute
    {
        private readonly string actionName;
    
        public HttpParamActionAttribute(string actionName)
        {
            this.actionName = actionName;
        }
    
        public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
        {
            if (actionName.Equals(methodInfo.Name, StringComparison.InvariantCultureIgnoreCase))
                return true;
    
            if (!actionName.Equals(this.actionName, StringComparison.InvariantCultureIgnoreCase))
                return false;
    
            var request = controllerContext.RequestContext.HttpContext.Request;
            return request[methodInfo.Name] != null;
        }
    }
    

    Controller

    [Authorize(Roles="CanAddContent")]
    public ActionResult CreateContent(Guid contentOwnerId)
    {
        var viewModel = new ContentViewModel
        {
            ContentOwnerId = contentOwnerId
            //populate rest of view model
        }
        return View("CreateContent", viewModel);
    }
    
    [Authorize(Roles="CanAddContent"), HttpPost, HttpParamAction("CreateContent"), ValidateAntiForgeryToken]
    public ActionResult SaveDraft(ContentFormModel model)
    {
        //Save as draft
        return RedirectToAction("CreateContent");
    }
    
    [Authorize(Roles="CanAddContent"), HttpPost, HttpParamAction("CreateContent"), ValidateAntiForgeryToken]
    public ActionResult Publish(ContentFormModel model)
    {
        //publish content
        return RedirectToAction("CreateContent");
    }
    

    View

    @using (Ajax.BeginForm("CreateContent", "MyController", new { contentOwnerId = Model.ContentOwnerId }))
    {
        @Html.AntiForgeryToken()
        @Html.HiddenFor(x => x.ContentOwnerId)
    
        <!-- Rest of your form controls -->
        <input name="SaveDraft" type="submit" value="SaveDraft" />
        <input name="Publish" type="submit" value="Publish" />
    }
    
    0 讨论(0)
  • 2020-11-21 07:30

    There are three ways by which you can solve the above issue

    1. HTML way
    2. Jquery way
    3. “ActionNameSelectorAttribute” way

    Below is a video which summarizes all the three approaches in a demonstrative way.

    https://www.facebook.com/shivprasad.koirala/videos/vb.100002224977742/809335512483940

    HTML way :-

    In the HTML way we need to create two forms and place the “Submit” button inside each of the forms. And every form’s action will point to different / respective actions. You can see the below code the first form is posting to “Action1” and the second form will post to “Action2” depending on which “Submit” button is clicked.

    <form action="Action1" method=post>
    <input type=”submit” name=”Submit1”/>
    </form>
    
    <form action="Action2" method=post>
    <input type=”submit” name=”Submit2”>
    </form>
    

    Ajax way :-

    In case you are a Ajax lover this second option would excite you more. In the Ajax way we can create two different functions “Fun1” and “Fun1” , see the below code. These functions will make Ajax calls by using JQUERY or any other framework. Each of these functions are binded with the “Submit” button’s “OnClick” events. Each of these function make call to respective action names.

    <Script language="javascript">
    function Fun1()
    {
    $.post(“/Action1”,null,CallBack1);
    }
    function Fun2()
    {
    $.post(“/Action2”,null,CallBack2);
    }
    </Script>
    
    <form action="/Action1" method=post>
    <input type=submit name=sub1 onclick=”Fun2()”/>
    </form>
    <form action="/Action2" method=post>
    <input type=submit name=sub2 onclick=”Fun1()”/>
    </form>
    

    Using “ActionNameSelectorAttribute”:-

    This is a great and a clean option. The “ActionNameSelectorAttribute” is a simple attribute class where we can write decision making logic which will decide which action can be executed.

    So the first thing is in HTML we need to put proper name’s to the submit buttons for identifying them on the server.

    You can see we have put “Save” and “Delete” to the button names. Also you can notice in the action we have just put controller name “Customer” and not a particular action name. We expect the action name will be decide by “ActionNameSelectorAttribute”.

    <form action=”Customer” method=post>
    <input type=submit value="Save" name="Save" /> <br />
    <input type=submit value="Delete" name="Delete"/>
    </form>
    

    So when the submit button is clicked , it first hits the “ActionNameSelector” attribute and then depending on which submit is fired it invokes the appropriate action.

    enter image description here

    So the first step is to create a class which inherits from “ActionNameSelectorAttribute” class. In this class we have created a simple property “Name”.

    We also need to override the “IsValidName” function which returns true or flase. This function is where we write the logic whether an action has to be executed or not. So if this function returns true then the action is executed or else it is not.

    public class SubmitButtonSelector : ActionNameSelectorAttribute
        {
            public string Name { get; set; }
            public override bool IsValidName(ControllerContext controllerContext, string actionName, System.Reflection.MethodInfo methodInfo)
            {
                // Try to find out if the name exists in the data sent from form
    var value = controllerContext.Controller.ValueProvider.GetValue(Name);
                if (value != null)
                {
                    return true;
                }
                return false;
    
            }
        }
    

    The main heart of the above function is in the below code. The “ValueProvider” collection has all the data that has been posted from the form. So it first looks up the “Name” value and if its found in the HTTP request it returns true or else it returns false.

    var value = controllerContext.Controller.ValueProvider.GetValue(Name);
    if (value != null)
          {
            return true;
          }
          return false;
    

    This attribute class can then decorated on the respective action and the respective “Name” value can be provided. So if the submit is hitting this action and if the name matches of the HTML submit button name it then executes the action further or else it does not.

    public class CustomerController : Controller
    {
            [SubmitButtonSelector(Name="Save")]
            public ActionResult Save()
            {
                return Content("Save Called");
            }
            [SubmitButtonSelector(Name = "Delete")]
            public ActionResult Delete()
            {
                return Content("Delete Called");
            }
    }
    
    0 讨论(0)
  • 2020-11-21 07:33

    I don't have enough rep to comment in the correct place, but I spent all day on this so want to share.

    While trying to implement the "MultipleButtonAttribute" solution ValueProvider.GetValue(keyValue) would incorrectly come back null.

    It turned out I was referencing System.Web.MVC version 3.0 when it should have been 4.0 (other assemblies are 4.0). I don't know why my project didn't upgrade correctly and I had no other obvious problems.

    So if your ActionNameSelectorAttribute is not working... check that.

    0 讨论(0)
提交回复
热议问题