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

2

7

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?

Waterman answered 23/10, 2020 at 11:36 Comment(0)
F
11

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

Fording answered 26/10, 2020 at 7:21 Comment(1)
There is a session exception (ModelState.IsValid == false because of that) with this approach despite me not configuring session at all. Doesn't work.Sanmiguel
P
4

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
}
Pergolesi answered 23/10, 2020 at 11:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.