首页 > 解决方案 > 在 _layout 和 index 页面之间的 asp.net core razor pages 中使用 asp-page 和 asp-route 的正确方法

问题描述

下面是文件结构

在此处输入图像描述

我在 Pages 文件夹下有默认索引页面,其布局为_LayoutHarman.cshmtl

代码:Pages/Shared/_LayoutHarman.chtml

标题菜单:在这种情况下,页面位于 subfolder.ie 类别文件夹中

    <a asp-route-cat_slug="electronic" asp-page="./category/Index">Electronic</a>
    <a asp-route-cat_slug="beauty-care" asp-page="./category/index" >Beauty Care</a>
    <a asp-route-cat_slug="toy" asp-page="./category/index" >Toy</a>

页脚菜单:页面位于根文件夹

<a asp-page="./Contact" >Contact</a>
<a asp-page="./terms" >Terms</a>
<a asp-page="./privacy" >Privacy</a>

代码:Pages/category/Index.cshtml

    @page "{cat_slug?}/{pageIndex:int?}"
    @model bList.Pages.category.IndexModel
@{
 }
    <nav aria-label="Page navigation example">
    <ul class="pagination text-center">
        @if(Model.prev_no!=0){
            <li><a asp-page="category" asp-route-cat_slug="@Model.cat_url" asp-route-pageIndex="@Model.prev_no">  Previous</a></li>
        }
        @if (Model.no_more_record != "YES")
        {
          <li><a asp-page="category"  asp-route-cat_slug="@Model.cat_url" asp-route-pageIndex="@Model.next_no">Next</a></li>
        }
    </ul>
    </nav>

这里 Next/previous 按钮生成 url 如下

https://localhost:8080/category/toy/1

https://localhost:8080/category/toy/2

https://localhost:8080/category/toy/3

分别在所选类别

问题:当我访问类别页面并单击上一个或下一个按钮,然后尝试单击链接联系人、条款、隐私即(位于 _LayoutHarman.cshtml 上)或标题菜单上时,href 变为 空白


编辑一:

代码:在 _LayoutHarman.cshtml 上

标题菜单:

<a  href="./category/toy" >toy</a>

页脚菜单

<a asp-page="./Contact" >Contact</a>
<a asp-page="./terms" >Terms</a>

代码:在 Category/Index.html 页面上

<a href="/category/@Model.cat_url/@Model.prev_no">Prev</a></li>
<a href="/category/@Model.cat_url/@Model.next_no">Next</a>

现在点击Next/Prev按钮,标题菜单生成 url 为 https://localhost:44382/category/toy/category/toy因此出现错误页面。但对于页脚菜单联系人/术语/隐私工作正常

标签: asp.net-corerazor-pagesasp.net-core-3.1

解决方案


我确实重现了您的问题,您需要delete the point(.)在.asp-page_LayoutHarman.cshmtl

改成这样:

<a asp-route-cat_slug="electronic" asp-page="/category/Index">Electronic</a>
<a asp-route-cat_slug="beauty-care" asp-page="/category/index" >Beauty Care</a>
<a asp-route-cat_slug="toy" asp-page="/category/index" >Toy</a>

<a asp-page="/Contact" >Contact</a>
<a asp-page="/terms" >Terms</a>
<a asp-page="/privacy" >Privacy</a>

而且不需要添加 asp-page="category"in Pages/category/Index.cshtml,在这个页面中删除这个属性即可。

这是我的测试结果:

在此处输入图像描述


推荐阅读