When I click on these buttons, it never calls these methods, instead calling another method(Index() method) which loads the view.
StartService() and StopService() redirect to Index. How are you determining StartService() and StopService() are not executing? Are you using the Visual Studio Debugger or the browser's dev tools?
Maybe this example will help? The Index view displays the action that redirected to the Index() Action.
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index(string? ActionName)
{
ViewData["ActionName"] = ActionName;
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult StartService()
{
return RedirectToAction("Index", new {ActionName = nameof(StartService) });
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult StopService()
{
return RedirectToAction("Index", new { ActionName = nameof(StopService) });
}
}
The View
@{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
<form asp-action="StartService" method="post">
<button type="submit" class="btn btn-primary">Start Service</button>
</form>
<form asp-action="StopService" method="post">
<button type="submit" class="btn btn-primary">Stop Service</button>
</form>
@if (ViewData["ActionName"] != null)
{
<div>
Action = @ViewData["ActionName"]
</div>
}