In this blog, I will explain how to use multiple submit buttons on one page or one form. So, here I will create a simple calculator using MVC. Let us see.

First, we have to create an MVC Project and then add a controller and create an action method.

ASP.NET

Click Ok.

ASP.NET

After that, we have to add a controller and add an Action method or change the name of Index.
  1. public ActionResult Calculate() {
  2. return View();
  3. }
  4. After that right click and add a view page
  5. @ {
  6. ViewBag.Title = "Calculate";
  7. }
  8. < style > td, th
  9. {
  10. padding: 10 px;
  11. }
  12. < /style>
  13. <div align="center">
  14. <h2>Simple Calculatar</h2> @using (Html.BeginForm()) {
  15. <table>
  16. <tr>
  17. <th> First Number </th>
  18. <td> <input type="text" id="txtFirstNumber" name="firstNumber" class="form-control" /> </td>
  19. </tr>
  20. <tr>
  21. <th> Last Number </th>
  22. <td> <input type="text" id="txtLastNumber" name="secondNumber" class="form-control" /> </td>
  23. </tr>
  24. <tr>
  25. <th><input type="submit" name="Cal" value="Add" class="btn btn-primary" /> <input type="submit" name="Cal" value="Sub" class="btn btn-primary" /> </th>
  26. <th> <input type="submit" name="Cal" value="Mul" class="btn btn-primary" /> <input type="submit" name="Cal" value="Div" class="btn btn-primary" /> </th>
  27. </tr>
  28. <tr>
  29. <th>Result</th>
  30. <td><input type="text" class="form-control" value="@ViewBag.Result" /> </td>
  31. </tr>
  32. </table> } </div>
In the above code, I have used a name attribute and given a common name. When I clicked a Submit button, it goes to the value according to action of that Submit button in controller. In controller, I took three parameters - one for first number and the second for the second number and a third for action value.

After that, we have to create a post method for performing the calculation.
  1. [HttpPost]
  2. public ActionResult Calculat(string firstNumber, string secondNumber, string Cal) {
  3. int a = Convert.ToInt32(firstNumber);
  4. int b = Convert.ToInt32(secondNumber);
  5. int c = 0;
  6. switch (Cal) {
  7. case "Add":
  8. c = a + b;
  9. break;
  10. case "Sub":
  11. c = a - b;
  12. break;
  13. case "Mul":
  14. c = a * b;
  15. break;
  16. case "Div":
  17. c = a / b;
  18. break;
  19. }
  20. ViewBag.Result = c;
  21. return View();
  22. }
Output
ASP.NET
Note
Here, I am using prameters which we can also use to view model class with strongly bind, form collection etc. Thank you and I hope this blog is beneficial to you.