首页 > 解决方案 > 从下拉菜单中将参数发送到相同的 url

问题描述

我正在尝试让多个菜单链接访问同一个剃须刀页面,但发送不同的参数以从数据库返回不同的结果。

通常我只会将该值附加到查询字符串并在单击新页面链接时检索它,但我不知道剃须刀页面如何做到这一点。例如,我想转到我的剃须刀页面 CourseList.cshtml,并通过会计作为值,所以我只能拉回会计课程。

asp-page="/CourseList?ccat=accounting"

我知道我可以为每个课程类别制作单独的 CourseList 页面,但这听起来很脏,并且随着新类别的添加将需要更高的维护。

<ul class="navbar-nav flex-grow-1">
                        <li class="nav-item dropdown">
                        <a class="nav-link text-dark dropdown-toggle" 
href="#" id="navbaddrop" data-toggle="dropdown">
                                Courses
                            </a>
                            <div class="dropdown-menu">
                                <a class="dropdown-item" asp-page="/CourseList?ccat=accounting">Accounting</a>
                                <a class="dropdown-item" asp-page="/CourseList?ccat=general">General</a>
                            <a class="dropdown-item" asp-page="/CourseList?ccat=it">IT</a>
                            <a class="dropdown-item" asp-page="/CourseList?ccat=manufacturing">Manufacturing</a>
                        </div>
                    </li>
</ul>

标签: bootstrap-4razor-pages

解决方案


如果您希望该值出现在查询字符串中,请将其传递给asp-route-*锚标记助手的参数:

<a class="dropdown-item" asp-page="/CourseList" asp-route-ccat="accounting">Accounting</a>

*替换为参数的名称。

或者,您可以通过在 Razor 页面中将路由数据参数指定为指令的一部分,将其作为路由参数(URL 中的段)传递@page

@page "{ccat}"

然后生成的链接将如下所示:

CourseList/accounting
CourseList/general

在页面本身中,您添加一个属性,该BindProperty属性表示应用了属性的参数:

public class CourseListModel : PageModel
{
    [BindProperty(SupportsGet=true)]
    public string Ccat { get; set; }

    ...

模型绑定将自动将查询字符串值分配给公共属性。更多信息:


推荐阅读