Search code examples
asp.net-corerazor-pages

How to properly generate link to razor page that doesn't change with route parameters


I am new to razor pages and obviously must be missing something, but for the life of me I can't figure out how to generate a link to a razor page that won't magically change and include optional route parameters - IF I'm on that page.

The issue I think stems from the link in question being in a nav menu that's always on the page - even when I'm on the page in question.

Specifically let's say my page is /Customer/Invoices. I've got a link in the menu that I've tried generating via the asp-page tag helper, Url.Page, etc. It works perfectly when I'm anywhere in the app, or even on the page in question, as long as I don't have any route parameters. If I access the page with a route parameter, then that menu link magically also has it.

To recap, if I browse to .../Customer/Invoices - the link is fine even when I'm on the page. If I browse to .../Customer/Invoices/123 - the link in the menu suddenly also has the 123 route parameter on the end.

I just want the static page url with no optional route parameter - regardless of whether or not I'm on the page in question with a route parameter. I have got to be missing something...

Any help would be appreciated.


Solution

  • Firstly,.net core tag helper will generate url with route parameters is by design.If you want to remove route parameters.Here are two solutions.

    1.set empty route parameter in <a> tag.Here is a demo:

    Page(Test1/Test):

    @page "{id?}"
    <a asp-page="Test" asp-route-id="1">link1</a>
    <a asp-page="Test" asp-route-id="">link2</a>
    

    result: enter image description here

    2.use href to replace <a> tag:

    Page(Test1/Test):

    @page "{id?}"
    <a asp-page="Test" asp-route-id="1">link1</a>
    <a href="/Test1/Test">link2</a>
    

    result: enter image description here