Sunday, December 20, 2015

ASP.NET MVC: Handling multiple submit buttons on the same form - MVC Razor


times you required to have more than one submit buttons on the same form in mvc razor. In that case, how will you handle the click event of different buttons on your form?
In this article, I am going to expose the various ways for handling multiple buttons on the same form. Suppose you have a user signup form like as below:

In the above fig. we have Save, Submit & Cancel buttons. Suppose on Save button click you are saving data in the tempUser table & on Submit button you are saving data in RegUser table and more over on Cancel button click you are returning to home page. For handling all of the above buttons click we have the three methods as mention below:

Method 1 - Submit the form for each button

In this way each submit button will post the form to server but provides the different values - Save, Submit and NULL respectively for the commands. On the basis of command name we can implement our own logic in the controller's action method.

MultipleCommand.cshtml

  1. @using (Html.BeginForm("MultipleCommand", "Home", FormMethod.Post, new { id = "submitForm" }))
  2. {
  3. <fieldset>
  4. <legend>Registration Form</legend>
  5. <ol>
  6. <li>
  7. @Html.LabelFor(m => m.Name)
  8. @Html.TextBoxFor(m => m.Name, new { maxlength = 50 })
  9. @Html.ValidationMessageFor(m => m.Name)
  10. </li>
  11. <li>
  12. @Html.LabelFor(m => m.Address)
  13. @Html.TextAreaFor(m => m.Address, new { maxlength = 200 })
  14. @Html.ValidationMessageFor(m => m.Address)
  15. </li>
  16. <li>
  17. @Html.LabelFor(m => m.MobileNo)
  18. @Html.TextBoxFor(m => m.MobileNo, new { maxlength = 10 })
  19. @Html.ValidationMessageFor(m => m.MobileNo)
  20. </li>
  21. </ol>
  22. <button type="submit" id="btnSave" name="Command" value="Save">Save</button>
  23. <button type="submit" id="btnSubmit" name="Command" value="Submit">Submit</button>
  24. <button type="submit" id="btnCancel" name="Command" value="Cancel" onclick="$('#submitForm').submit()">Cancel (Server Side)</button>
  25. </fieldset>
  26. }

Action Method in Controller


Method 2 - Introducing Second From

We can also introduce the second form for handling Cancel button click. Now, on Cancel button click we will post the second form and will redirect to the home page.

MultipleCommand.cshtml

  1. @using (Html.BeginForm("MultipleCommand", "Home", FormMethod.Post, new { id = "submitForm" }))
  2. {
  3. <fieldset>
  4. <legend>Registration Form</legend>
  5. <ol>
  6. <li>
  7. @Html.LabelFor(m => m.Name)
  8. @Html.TextBoxFor(m => m.Name, new { maxlength = 50 })
  9. @Html.ValidationMessageFor(m => m.Name)
  10. </li>
  11. <li>
  12. @Html.LabelFor(m => m.Address)
  13. @Html.TextAreaFor(m => m.Address, new { maxlength = 200 })
  14. @Html.ValidationMessageFor(m => m.Address)
  15. </li>
  16. <li>
  17. @Html.LabelFor(m => m.MobileNo)
  18. @Html.TextBoxFor(m => m.MobileNo, new { maxlength = 10 })
  19. @Html.ValidationMessageFor(m => m.MobileNo)
  20. </li>
  21. </ol>
  22. <button type="submit" id="btnSave" name="Command" value="Save">Save</button>
  23. <button type="submit" id="btnSubmit" name="Command" value="Submit">Submit</button>
  24. <button type="submit" id="btnCancelSecForm" name="Command" value="Cancel" onclick="$('#cancelForm').submit()"> Cancel (Server Side by Second Form)</button>
  25. </fieldset>
  26. }
  27. @using (Html.BeginForm("MultipleButtonCancel", "Home", FormMethod.Post, new { id = "cancelForm" })) { }

Action Method in Controller


Method 3 - Introducing Client Side Script

We can also use javascript or jquery for handling Cancel button click. Now, on Cancel button click we will directly redirect to the home page. In this way, there is no server side post back and this is the more convenient way to handle the cancel button click.

MultipleCommand.cshtml

  1. <button type="submit" id="btnSave" name="Command" value="Save">Save</button>
  2. <button type="submit" id="btnSubmit" name="Command" value="Submit">Submit</button>
  3. <button name="ClientCancel" type="button" onclick=" document.location.href = $('#cancelUrl').attr('href');">Cancel (Client Side)</button>
  4. <a id="cancelUrl" href="@Html.AttributeEncode(Url.Action("Index", "Home"))" style="display:none;"></a>
What do you think?
I hope you will enjoy these tricks while programming with MVC Razor. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome. You can download demo project in MVC4 from below link.



USING Selector


1) Dirty one

<input type="submit" id="Submit1" name="btnSubmit", value="action:First" />
<input type="submit" id="Submit2" name="btnSubmit", value="action:Second" />

[HttpPost]
public ActionResult MyAction(string btnSubmit, MyFormModel model)
{
  switch (btnSubmit) {
    case "action:First":
      /* Your code */
      break;
    case "action:Second":
      /* Your code */
      break;
  }


2) Nicer - refactor code above to attribute
Like idea from
http://blog.maartenballiauw.be/post/2009/11/26/Supporting-multiple-submit-buttons-on-an-ASPNET-MVC-view.aspx[^]

Rephrasing code in article above:
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class MultipleButtonAttribute : ActionNameSelectorAttribute
{
    public string Name { get; set; }
    public string Argument { get; set; }
 
    public override bool IsValidName(ControllerContext controllerContext,
string actionName, MethodInfo methodInfo)
    {
        bool isValidName = false;
        string keyValue = string.Format("{0}:{1}", Name, Argument);
        var value = controllerContext.Controller.ValueProvider.GetValue(keyValue);
        if (value != null)
        {
            controllerContext.Controller.ControllerContext.RouteData.Values[Name] = Argument;
            isValidName = true;
        }
 
        return isValidName;
    }
}

and your code
[HttpPost]
 [MultipleButton(Name = "action", Argument = "First")]
 public ActionResult First(MyFormModel model) { ... }
 
 [HttpPost]
 [MultipleButton(Name = "action", Argument = "Second")]
 public ActionResult Second(MyFormModel model) { ... }


OPTION2

public class HttpParamActionAttribute : ActionNameSelectorAttribute {
    public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo) {
        if (actionName.Equals(methodInfo.Name, StringComparison.InvariantCultureIgnoreCase))
            return true;

        if (!actionName.Equals("Action", StringComparison.InvariantCultureIgnoreCase))
            return false;
        
        var request = controllerContext.RequestContext.HttpContext.Request;
        return request[methodInfo.Name] != null;
    }
}
How to use it? Just have a form similar to this:
<% using (Html.BeginForm("Action", "Post")) { %>
  <!— …form fields… -->
  <input type="submit" name="saveDraft" value="Save Draft" />
  <input type="submit" name="publish" value="Publish" />
<% } %>
and controller with two methods
public class PostController : Controller {
    [HttpParamAction]
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult SaveDraft(…) {
        //…
    }

    [HttpParamAction]
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Publish(…) {
        //…
    }
}

Option 3