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.
Click Ok.
After that, we have to add a controller and add an Action method or change the name of Index.
- public ActionResult Calculate() {
- return View();
- }
- After that right click and add a view page
- @ {
- ViewBag.Title = "Calculate";
- }
- < style > td, th
- {
- padding: 10 px;
- }
- < /style>
- <div align="center">
- <h2>Simple Calculatar</h2> @using (Html.BeginForm()) {
- <table>
- <tr>
- <th> First Number </th>
- <td> <input type="text" id="txtFirstNumber" name="firstNumber" class="form-control" /> </td>
- </tr>
- <tr>
- <th> Last Number </th>
- <td> <input type="text" id="txtLastNumber" name="secondNumber" class="form-control" /> </td>
- </tr>
- <tr>
- <th><input type="submit" name="Cal" value="Add" class="btn btn-primary" /> <input type="submit" name="Cal" value="Sub" class="btn btn-primary" /> </th>
- <th> <input type="submit" name="Cal" value="Mul" class="btn btn-primary" /> <input type="submit" name="Cal" value="Div" class="btn btn-primary" /> </th>
- </tr>
- <tr>
- <th>Result</th>
- <td><input type="text" class="form-control" value="@ViewBag.Result" /> </td>
- </tr>
- </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.
- [HttpPost]
- public ActionResult Calculat(string firstNumber, string secondNumber, string Cal) {
- int a = Convert.ToInt32(firstNumber);
- int b = Convert.ToInt32(secondNumber);
- int c = 0;
- switch (Cal) {
- case "Add":
- c = a + b;
- break;
- case "Sub":
- c = a - b;
- break;
- case "Mul":
- c = a * b;
- break;
- case "Div":
- c = a / b;
- break;
- }
- ViewBag.Result = c;
- return View();
- }
Output
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.