I created a fresh Razor Pages project in ASP.NET Core and made the following changes to the Index.cshtml
and Privacy.cshtml
files:
// Index.cshtml
@page "/"
@model IndexModel
// Privacy.cshtml
@page "/privacy"
@model PrivacyModel
// _Layout.cshtml
<li class="nav-item">
<a class="nav-link text-dark" asp-page="/">Home</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-page="/privacy">Privacy</a>
</li>
// Rendered HTML
<a class="nav-link text-dark" href="">Home</a>
<a class="nav-link text-dark" href="/privacy">Privacy</a>
Why do the @page "/"
using asp-page="/"
render with empty href attributes?
See https://www.learnrazorpages.com/razor-pages/tag-helpers/anchor-tag-helper:
The path to the target Razor page must be provided without the file extension. The leading
/
specifies an absolute path. If you omit it, the framework looks for a page relative to the current one:
<a asp-page="/page">Click</a>
If no valid page name is specified, the tag helper will render the
href
attribute with an empty string. If you want to generate a link to the default page in a folder, you must still include the default page's file name:
<a asp-page="/folder/index">Folder</a>
This renders as
<a href="/folder">Folder</a>
The tag helper will generate an
href
attribute whose value will be taken from the route template of the specified page.
So, you must include "Index" as part of the asp-page
attribute if the endpoint is represented by a page named "Index":
<a asp-page="/Index">Home</a>
By the way, the changes you made to the template pages will have no practical effect because those routes are generated by default anyway.