Multiple submit actions with multiple submit buttons in asp net core razor page

Viewed 3950

I have a razor page with a form and multiple submit buttons. with each button I want to start a different Post action in my codebehind file. so this is in my cshtml page:

<form class="form" method="post" >
    <input type="submit" value="Test1" formaction="Button1" />
    <input type="submit" value="Test2" formaction="Button2" />
</form>

and this in my cshtml.cs file:

[HttpPost]
public IActionResult Button1(IFormCollection data)
{
//my code
}

[HttpPost]
public IActionResult Button2(IFormCollection data)
{
//my code
}

Unfortunately, this is not working. when I submit I get a 404 error:

This localhost page can’t be found No webpage was found for the web address: https://localhost:44366/Mutations/Button1 HTTP ERROR 404

The correct URL should be: https://localhost:44366/Mutations/Test

What am I doing wrong?

2 Answers

Because you are a project in Razor, the routing rules in Razor are different from MVC projects, you can change your code as follows:

Your cshtml.cs file:

 public IActionResult OnPostButton1(IFormCollection data)
    {
        //...
    }

   
    public IActionResult OnPostButton2(IFormCollection data)
    {
        //...
    }

Your cshtml page:

<form class="form" method="post">
    <input type="submit" value="Test1" asp-page-handler="Button1"/>
    <input type="submit" value="Test2"  asp-page-handler="Button2"/>
</form>

Result: enter image description here

You must assign different routes (that match your formaction) to both actions:

[HttpPost("button1")]
public IActionResult Button1(IFormCollection data)
{
//my code
}

[HttpPost("button2")]
public IActionResult Button2(IFormCollection data)
{
//my code
}
Related