8

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 2

14

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

Sign up to request clarification or add additional context in comments.

1 Comment

There is a session exception (ModelState.IsValid == false because of that) with this approach despite me not configuring session at all. Doesn't work.
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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.