我的网站导航栏上有一个类别下拉过滤器,它会影响所有页面。我不想为它创建一个单独的视图。
使用过滤器时,我希望在查询字符串前面添加
?filter=category+selected
。
例如,我的查询字符串应该是
https://website.com/controller_name/action_name?filter=category+selected
有办法实现这一点吗?任何建议表示赞赏。
在你看来,使用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 来更新选项。