Search code examples
c#asp.net-corerazorrazor-pages

Razor Page - 400 error when using the "action" tag to redirect to url when clicking on a button wrapped in a form


I have a property Url in my page Model that I have set up as a [BindProperty]. This property contains the url I want to redirect to when a user clicks on the Back Button. However when I click on the back button I get a 400 error even though I can see the url string has been correctly added to the url.

If I then simply refresh the page, the page I want to redirect to loads as expected.

Why am I getting a 400 error? and how can I stop it from happening?

cshtml page:

@page "{id:int}"
@model AppName.AppVariablesModel
@{
    ViewData["Title"] = "AppVariables";
}
<br />
<h2 style="text-align:center">App Variables</h2>
<br/>
<table style="margin-left:auto; margin-right:auto; cursor:default; width:50%;" class="table-bordered center">
    @foreach (var dict in Model.AppVariablesDict)
    {
        <tr style="cursor:default;">
            <th style="color:white;">@dict.Key</th>
            <td style="color:black;">@dict.Value</td>
        </tr>
    }
</table>
<br/>
<form action="@Model.Url" method="POST">
    <body style="text-align:center">
        <button type="submit" style="color:black;" class="btn-sm ml-auto mr-1" title="Back">
            Back
        </button>
    </body>
</form>

cshtml.cs page:

namespace AppName
{
    public class AppVariablesModel : PageModel
    {
       [BindProperty]
        public string Url { get; set; }
    }

public void OnGet(int id, string db, string server, string url)
        {
           Url = url;
        }

Solution

  • Your form is using the http POST verb but you are trying to command using the GET verb. It can't route on a form post in this manner. You are mismatched.

    Key things to look at:

    form action="@Model.Url" method="POST"

    public void OnGet

    Either change your form method to use Get instead or implement a OnPost() method instead of the OnGet