Thursday, 12 October 2017

MVC handle multiple submit buttons in ASP.NET MVC.

In MVC we can handle the multiple submit buttons in same post type action. The following code snipt will help you to implement this kind of scenario.

Step 1: Add the following two actions in your MVC controller.

public ActionResult Test()
{
  return View();
}

[HttpPost]

public ActionResult Test(string submitBtn)
{
  switch (submitBtn)
  {
    case "Save":
    //Perform save functionality.
    break;
    case "Cancel":
    //Manage cancel button click
    break;
  }
  return View();
}


Step 2: Now create new view with following html. In this html you can see two submit buttons in one Form. So everytime when we will click on any submit button then the "Test" method will be called.

@{
    ViewBag.Title = "Test";
}

<h2>TestR</h2>


@using (Html.BeginForm("Test", "Home", FormMethod.Post))

{
    <input type="text" name="FirstName" />
    <input type="submit" name="submitBtn" value="Save" />
    <input type="submit" name="submitBtn" value="Cancel" />
}

How we know that the which submit button has been clicked? To find the solution of this we have following solution:-

1. Give the same name to both of Submit buttons. As you can see the same name of both controls in following html.
@using (Html.BeginForm("Test", "Home", FormMethod.Post))
{
    <input type="text" name="FirstName" />
    <input type="submit" name="submitBtn" value="Save" />
    <input type="submit" name="submitBtn" value="Cancel" />
}
2. In the Test Action in the Controller take the parameter named "submitBtn" with type of string.
Note: The name of this parameter should be same as the name of the submit buttons. 

No comments:

Post a Comment