FormMethod.Get with Html.BeginForm gives error in ASP.NET Core MVC

64 Views Asked by At

I an trying to implement a search query string for my searchbar.

Following the Microsoft documentation: Adding search, it suggested using Html.BeginForm("action", "controller", FormMethod.Get) method in view when I got the error:

This page isn’t working

If the problem continues, contact the site owner.

HTTP ERROR 405

My search query string shows:

localhost:7185/Searchbar__RequestVerificationToken=CfDJ8GCygMwCAINPiWbEfcvWp986TX925YtT_ivBMr4CJ0Cj6g6BDdH6xua1gReYA37rr5ljwc_GCuVXkANiQOt6hWJVJpOLr308aqLyyO6ii9fpf6DIbDlkKxYtOHHrN-O5eOxj4ie-TU-C-uBX2CNp0x4&SearchString=a&__RequestVerificationToken=CfDJ8GCygMwCAINPiWbEfcvWp986TX925YtT_ivBMr4CJ0Cj6g6BDdH6xua1gReYA37rr5ljwc_GCuVXkANiQOt6hWJVJpOLr308aqLyyO6ii9fpf6DIbDlkKxYtOHHrN-O5eOxj4ie-TU-C-uBX2CNp0x4

I have used [ValidateAntiForgeryToken] in the controller:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Index(string searchString)
{
    //Code
}

Along with @Html.AntiForgeryToken() in the view:

@using (Html.BeginForm("Index", "Searchbar", FormMethod.Get))
{
    @Html.AntiForgeryToken()
    <form class="d-flex w-50 ps-lg-5" role="search" asp-controller="Searchbar" asp-action="Index">
        <div class="input-group">
            <input class="form-control shadow-none" value="@TempData["searchString"]" type="search" placeholder="Search" id="text-suggestion" aria-label="Search" name="SearchString"
                   required oninvalid="this.setCustomValidity(' ')" />
            <button class="btn btn-outline-success shadow-none" type="submit" id="search-button"><i class='bx bx-search'></i></button>
        </div>
    </form>
}
1

There are 1 best solutions below

0
ZNAXNOR On

This is my Solution


  • Remove [HttpPost] from controller action.
    • As using FormMethod.Get with Html.BeginForm will render to <form method="get">, you cannot use [HttpPost] in controller which renders to <form method="post">.
public async Task<IActionResult> Index(string searchString)
{
    //Code
}
  • Remove <form> element from View
    • As Html.BeginForm renders a <form> element, your existing <form> tag-helper will behave as a child element.
    • Even without following this step your page will render, but this will cause the search query string to behave weirdly.
@using (Html.BeginForm("Index", "Searchbar", FormMethod.Get))
{
    <div class="input-group d-flex ps-lg-5">
        <input class="form-control shadow-none" value="@TempData["searchString"]" type="search" placeholder="Search" id="text-suggestion" aria-label="Search" name="SearchString"
                required oninvalid="this.setCustomValidity(' ')" />
        <button class="btn btn-outline-success shadow-none" type="submit" id="search-button"><i class='bx bx-search'></i></button>
    </div>
}

Thank you.