asp.net core Button -Post method in Controller

Santhi Dhanuskodi 265 Reputation points
2024-04-11T16:42:45.8266667+00:00

Hi,

I have asp.net core web app with index.cshtml. This has only 2 buttons 'Startservice' and 'stopservice'.

I have homecontroller with httppost methods. When I click on these buttons, it never calls these methods, instead calling another method(Index() method) which loads the view.

my index.cshtml is

@{

**ViewData["Title"] = "Test app";**

}

<h1>Test app</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-danger">Stop Service</button>**

</form>

my homecontroller is

public class HomeController : Controller

{

**private readonly myappwatcher _watcher;**

**public HomeController(myappwatcher watcher)**

**{**

    **_watcher = watcher;**

**}**

**public IActionResult Index()**

**{**

    **return View();**

**}**

**[HttpPost]**

**[ValidateAntiForgeryToken]**

**public IActionResult StartService()**

**{**

    **_watcher.Start(); // Start the background service**

    **return RedirectToAction("Index");**

**}**

**[HttpPost]**

**[ValidateAntiForgeryToken]**

**public IActionResult StopService()**

**{**

    **_watcher.Stop(); // Stop the background service**

    **return RedirectToAction("Index");**

**}**

}

I tried various buttons like <input> and chnaged several attributes...but still not able to solve the issue.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,557 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. AgaveJoe 28,371 Reputation points
    2024-04-11T17:04:29.8733333+00:00

    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>
    }
    
    

  2. Santhi Dhanuskodi 265 Reputation points
    2024-04-12T03:43:18.0566667+00:00

    It is still the same issue, I tried both codes(Bruce and Agavejoe).

    I tried accessing the app as 'https://localhost:8080' and 'https://localhost:8080:Home/Index' ...it loads the index page in both cases.

    Adding my program.cs

    namespace GraphQL_Harp_Data

    {

    **public class Program**
    
    **{**
    
        **public static void Main(string[] args)**
    
        **{**
    
            **CreateHostBuilder(args).Build().Run();**
    
        **}**
    
        **public static IHostBuilder CreateHostBuilder(string[] args) =>**
    
            **Host.CreateDefaultBuilder(args)**
    
                **.ConfigureWebHostDefaults(webBuilder =>**
    
                **{**
    
                    **webBuilder.UseUrls("http://*:8080");**
    
                    **webBuilder.UseStartup<Startup>();**
    
                **});**
    
    **}**
    ```**}**
    
    And startup.cs file
    
    ```typescript
    **public void ConfigureServices(IServiceCollection services)**
    
    **{**
    
        **services.AddAuthorization();**
    
        **services.AddControllersWithViews();**
    
        **// Register services and dependencies**
    
        **services.AddSingleton<MyAppWatcher>();**
    
    **}**
    
    **// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.**
    
    **public void Configure(IApplicationBuilder app, IWebHostEnvironment env)**
    
    **{**
    
        **if (env.IsDevelopment())**
    
        **{**
    
            **app.UseDeveloperExceptionPage();**
    
        **}**
    
        **else**
    
        **{**
    
            **app.UseExceptionHandler("/Home/Error");**
    
            **app.UseHsts();**
    
        **}**
    
        **app.UseHttpsRedirection();**
    
        **app.UseStaticFiles();**
    
        **app.UseRouting();**
    
        **app.UseAuthorization();**
    
        **app.UseEndpoints(endpoints =>**
    
        **{**
    
            **endpoints.MapControllerRoute(**
    
                **name: "Index",**
    
                **pattern: "{controller=Home}/{action=Index}/{id?}");**
    
        **});**
    
     **}**
    ```**}**
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.