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

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

    Something I don't like about ActionSelectName is that IsValidName is called for every action method in the controller; I don't know why it works this way. I like a solution where every button has a different name based on what it does, but I don't like the fact that you have to have as many parameters in the action method as buttons in the form. I have created an enum for all button types:

    public enum ButtonType
    {
        Submit,
        Cancel,
        Delete
    }
    

    Instead of ActionSelectName, I use an ActionFilter:

    public class MultipleButtonsEnumAttribute : ActionFilterAttribute
    {
        public Type EnumType { get; set; }
    
        public MultipleButtonsEnumAttribute(Type enumType)
        {
            EnumType = enumType;
        }
    
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            foreach (var key in filterContext.HttpContext.Request.Form.AllKeys)
            {
                if (Enum.IsDefined(EnumType, key))
                {
                    var pDesc = filterContext.ActionDescriptor.GetParameters()
                        .FirstOrDefault(x => x.ParameterType == EnumType);
                    filterContext.ActionParameters[pDesc.ParameterName] = Enum.Parse(EnumType, key);
                    break;
                }
            }
        }
    }
    

    The filter will find the button name in the form data and if the button name matches any of the button types defined in the enum, it will find the ButtonType parameter among the action parameters:

    [MultipleButtonsEnumAttribute(typeof(ButtonType))]
    public ActionResult Manage(ButtonType buttonPressed, ManageViewModel model)
    {
        if (button == ButtonType.Cancel)
        {
            return RedirectToAction("Index", "Home");
        }
        //and so on
        return View(model)
    }
    

    and then in views, I can use:

    
    
    

提交回复
热议问题