ASP.NET Core MVC 中全局过滤器的查询字符串

问题描述 投票:0回答:1

我的网站导航栏上有一个类别下拉过滤器,它会影响所有页面。我不想为它创建一个单独的视图。

使用过滤器时,我希望在查询字符串前面添加

?filter=category+selected

例如,我的查询字符串应该是

https://website.com/controller_name/action_name?filter=category+selected

有办法实现这一点吗?任何建议表示赞赏。

c# asp.net-core-mvc global-filter
1个回答
0
投票

在你看来,使用js脚本:

function filterQuery() {
    let selectedCategory = document.getElementById("dropdownId").value;
    
    let url = "/ControllerName/ActionName?filter=" + encodeURIComponent(selectedCategory);
    
    window.location.href = url;
}

下拉菜单将发生变化:

<select id="dropdownId" onchange="filterQuery()">
    @foreach (var category in Model.Categories)
    {
        <option value="@category">@category</option>
    }
</select>

控制器动作

public IActionResult ActionName(string filter)
{
    var dropdownDataModel = GetData();

    if (!string.IsNullOrWhiteSpace(filter))
    {
        //Filter code
    }
    
    return View(dropdownDataModel);
}

如果您不想重新加载页面,也可以使用 fetch API 来更新选项。

© www.soinside.com 2019 - 2024. All rights reserved.