Brian
Brian

Reputation: 1989

Why am I getting a 404 error when I submit my Blazor Server form?

I created a new Blazor Server project in Visual Studio 2019 using .NET Core 5.x.

I created a new page Search.razor and put it in the /Pages directory.

I created a new page SearchResults.razor and put it in the /Pages directory.

My Search.razor looks like this:

@page "/search"

<h3>Search</h3>

<form method="GET" action="SearchResults.razor">
    <input type="text" id="name" name="name" />
    ... future form elements here
    <button type="submit"> Submit </button>
</form>

@code {

}

My SearchResults.razor looks like this:

@page "/searchresults"

<h3>SearchResults</h3>

@code {

}

I modified the /Shared/NavMenu.razor page to look like this:

<div class="@NavMenuCssClass" @onclick="ToggleNavMenu">
    <ul class="nav flex-column">
        ...
        <li class="nav-item px-3">
            <NavLink class="nav-link" href="search">
                <span class="oi oi-list-rich" aria-hidden="true"></span> Search
            </NavLink>
        </li>
    </ul>
</div>

I start the app, click the "Search" link in the right menu, enter the name "joe smith" into the search field, click the Submit button, and receive this from Chrome:

This localhost page can’t be found
No webpage was found for the web address:
https://localhost:44314/SearchResults.razor?name=joe+smith
HTTP ERROR 404

The address bar contains this:

https://localhost:44314/SearchResults.razor?name=joe+smith

Upvotes: 1

Views: 887

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273264

"SearchResults.razor" is not a valid address.

A quick sketch of how it could work:

@page "/search"
<EditForm Model="this" OnValidSubmit="DoSearch">
    <InputText @bind-Value="search" />
    <button type="submit">Submit</button>
</EditForm>

@code {
    private string search;
    void DoSearch()
    {
        var arg = System.Web.HttpUtility.UrlEncode(search);
        Navigator.NavigateTo($"searchresults/{arg}");
    }
}

and the receiving end, UrlDecode comes for free:

@page "/searchresults/{text?}"
<h3>SearchResults</h3>
<p>Looking for @Text</p>    

@code {

  [Parameter] public string Text { get; set; }


}

Upvotes: 2

Related Questions