Search code examples
asp.net-corerazor-pages.net-7.0

asp.net 7 razor pages 'Get' form submit not producing expected url


Goal/expectation: have a url that looks like: /search/test

Problem: I'm getting: /search?myvar=test

Cshtml

@page "{handler?}/{myvar?}"

<form method="get" asp-route-handler="search">
    <input name="myvar" value="test" >
    <button type="submit">Search</button>
</form>

Cshtml.cs

public void OnGetSearch(string myvar)

Hi guys, from my understanding setting @page "{handler?}/{myvar?}" should have produced my expected url format.

Just in case it makes any difference, I also have a standard public void OnGet() for accessing the page directly instead of via form submit. (The form is on the same page, and submits to itself but with the search handler)

I've re-read the docs a couple of times but not seeing what I'm doing wrong.

Can someone suggest what I'm doing wrong?

Thanks


Solution

  • I think you misunderstand the role of @page. When you supply a route template to the @page directive, you specify a URL pattern that the page can respond to. @page cannot limit the format of the url generated by the form, it can only limit the format of the url that the current page can accept.

    As the specifications (RFC1866, page 46; HTML 4.x section 17.13.3) state:

    If the method is "get" and the action is an HTTP URI, the user agent takes the value of action, appends a `?' to it, then appends the form data set, encoded using the "application/x-www-form-urlencoded" content type.

    When you use the get method to submit a form, it will put all the values into query string instead of route. So you didn't do anything wrong, you just misunderstand the role of @page.