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

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

    I'm pretty late to the party, but here goes... My implementation borrows from @mkozicki but requires less hardcoded strings to get wrong. Framework 4.5+ required. Essentially, the controller method name should be the key to the routing.

    Markup. The button name must be keyed with "action:[controllerMethodName]"

    (notice the use of the C#6 nameof API, providing type-specific reference to the name of the controller method you wish to invoke.

    ... form fields ....

    Controller:

    namespace MyApp.Controllers
    {
        class MyController
        {    
            [SubmitActionToThisMethod]
            public async Task FundDeathStar(ImperialModel model)
            {
                await TrainStormTroopers();
                return View();
            }
    
            [SubmitActionToThisMethod]
            public async Task HireBoba(ImperialModel model)
            {
                await RepairSlave1();
                return View();
            }
        }
    }
    

    Attribute Magic. Notice the use of CallerMemberName goodness.

    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class SubmitActionToThisMethodAttribute : ActionNameSelectorAttribute
    {        
        public SubmitActionToThisMethodAttribute([CallerMemberName]string ControllerMethodName = "")
        {
            controllerMethod = ControllerMethodName;
            actionFormat = string.Concat(actionConstant, ":", controllerMethod);
        }
        const string actionConstant = "action";
        readonly string actionFormat;
        readonly string controllerMethod;
    
        public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
        {
            var isValidName = false;
            var value = controllerContext.Controller.ValueProvider.GetValue(actionFormat);
    
            if (value != null)
            {
                controllerContext.Controller.ControllerContext.RouteData.Values[actionConstant] = controllerMethod;
                isValidName = true;
            }
            return isValidName;
        }
    }
    

提交回复
热议问题