In this article I will explain with an example, how to use multiple Submit Buttons inside View in ASP.Net Core MVC.
Multiple Submit Buttons will be placed inside a single Form and each Button will call a different Action Method in ASP.Net Core MVC.
Controller
The Controller consists of following three Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
Save Action method for handling POST operation – Button 1
This Action method gets called when Save button is clicked.
Inside this Action method a string message is set in TempData object indicating that the Save button is clicked and then it redirects to Index Action method.
Cancel Action method for handling POST operation – Button 2
This Action method gets called when Cancel button is clicked.
Inside this Action method a string message is set in TempData object indicating that the Save button is clicked and then it redirects to Index Action method.
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Save()
{
TempData["Message"] = "You clicked Save!";
return RedirectToAction("Index");
}
[HttpPost]
public IActionResult Cancel()
{
TempData["Message"] = "You clicked Cancel!";
return RedirectToAction("Index");
}
}
View
The View consists of an HTML Form which has been created using the following ASP.Net Tag Helpers attributes.
asp-controller – Name of the Controller. In this case the name is Home.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The Form consists of two HTML Submit buttons.
The Submit Buttons has been set with the POST Action method using the asp-action attribute.
When the Submit Buttons are clicked, the Form gets submitted.
At the end, there’s a JavaScript method that displays the TempData object message using JavaScript Alert Message Box.
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form method="post" asp-controller="Home">
<input type="submit" value="Save" asp-action="Save" />
<input type="submit" value="Cancel" asp-action="Cancel" />
</form>
@if (TempData["Message"] != null)
{
<script type="text/javascript">
window.onload = function () {
alert('@TempData["Message"]');
};
</script>
}
</body>
</html>
Screenshot
Downloads