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

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

    Give your submit buttons a name, and then inspect the submitted value in your controller method:

    <% Html.BeginForm("MyAction", "MyController", FormMethod.Post); %>
    
    
    <% Html.EndForm(); %>
    

    posting to

    public class MyController : Controller {
        public ActionResult MyAction(string submitButton) {
            switch(submitButton) {
                case "Send":
                    // delegate sending to another controller action
                    return(Send());
                case "Cancel":
                    // call another action to perform the cancellation
                    return(Cancel());
                default:
                    // If they've submitted the form without a submitButton, 
                    // just return the view again.
                    return(View());
            }
        }
    
        private ActionResult Cancel() {
            // process the cancellation request here.
            return(View("Cancelled"));
        }
    
        private ActionResult Send() {
            // perform the actual send operation here.
            return(View("SendConfirmed"));
        }
    
    }
    

    EDIT:

    To extend this approach to work with localized sites, isolate your messages somewhere else (e.g. compiling a resource file to a strongly-typed resource class)

    Then modify the code so it works like:

    <% Html.BeginForm("MyAction", "MyController", FormMethod.Post); %>
    
    
    <% Html.EndForm(); %>
    

    and your controller should look like this:

    // Note that the localized resources aren't constants, so 
    // we can't use a switch statement.
    
    if (submitButton == Resources.Messages.Send) { 
        // delegate sending to another controller action
        return(Send());
    
    } else if (submitButton == Resources.Messages.Cancel) {
         // call another action to perform the cancellation
         return(Cancel());
    }
    

提交回复
热议问题