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

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

    Based on mkozicki answer I come up with a bit different solution. I still use ActionNameSelectorAttribute But I needed to handle two buttons 'Save' and 'Sync'. They do almost the same so I didn't want to have two actions.

    attribute:

    public class MultipleButtonActionAttribute : ActionNameSelectorAttribute
    {        
        private readonly List AcceptedButtonNames;
    
        public MultipleButtonActionAttribute(params string[] acceptedButtonNames)
        {
            AcceptedButtonNames = acceptedButtonNames.ToList();
        }
    
        public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
        {            
            foreach (var acceptedButtonName in AcceptedButtonNames)
            {
                var button = controllerContext.Controller.ValueProvider.GetValue(acceptedButtonName);
                if (button == null)
                {
                    continue;
                }                
                controllerContext.Controller.ControllerContext.RouteData.Values.Add("ButtonName", acceptedButtonName);
                return true;
            }
            return false;
        }
    }
    

    view

    
    
    

    controller

     [MultipleButtonAction("Save", "Sync")]
     public ActionResult Sync(OrgSynchronizationEditModel model)
     {
         var btn = this.RouteData.Values["ButtonName"];
    

    I also want to point out that if actions do different things I would probably follow mkozicki post.

提交回复
热议问题