You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ASP.NET Core路由中处理锚点点击实现多参数数据筛选

.NET 6 MVC多参数筛选锚点链接实现方案

问题场景

使用.NET 6 MVC项目模板实现FAQ数据筛选,已完成单属性(分类/主题)筛选,但连续点击不同属性时,无法保留已选参数生成组合筛选链接。例如先点击分类gen后再点击主题bs,期望链接为https://localhost:7026/home/index/category/gen/topic/bs,但当前仅能生成单参数链接。

解决方案

1. 传递当前筛选参数到视图

修改控制器,将当前请求中的topicId和categoryId存入ViewBag,供视图生成链接时使用:

public IActionResult Index(string? topicId, string? categoryId)
{
    List<FAQ> faqList = _dbContext.FAQs.Include(t => t.Topic).Include(c => c.Category).ToList();

    if (!string.IsNullOrEmpty(topicId))
    {
        faqList = faqList.Where(x => x.TopicId == topicId.ToUpper()).ToList();
    }
    if (!string.IsNullOrEmpty(categoryId))
    {
        faqList = faqList.Where(x => x.CategoryId == categoryId.ToUpper()).ToList();
    }

    var categories = _dbContext.Categories.ToList();
    ViewBag.Categories = categories;
    // 传递当前筛选参数至视图
    ViewBag.CurrentTopicId = topicId;
    ViewBag.CurrentCategoryId = categoryId;

    return View(faqList);
}

2. 动态生成带组合参数的锚点链接

在视图中生成RouteLink时,带上当前已选的筛选参数,让路由系统自动匹配多参数路由:

分类筛选锚点修改

@foreach (var category in ViewBag.Categories)
{
    <tr>
        <td>
            @Html.RouteLink((string)category.Name, 
                "category_topic", // 使用支持双参数的路由名称
                new { 
                    controller = "Home", 
                    action = "Index", 
                    categoryId = category.CategoryId,
                    topicId = ViewBag.CurrentTopicId // 保留当前已选主题ID
                }, 
                new{ @class="text-decoration-none" })
        </td>
    </tr>
}

主题筛选锚点修改

<li class="nav-item">
    @Html.RouteLink("Bootstrap", 
        "category_topic", 
        new { 
            controller = "Home", 
            action = "Index", 
            topicId = "BS",
            categoryId = ViewBag.CurrentCategoryId // 保留当前已选分类ID
        }, 
        new{ @class="nav-link text-dark" })
</li>
<li class="nav-item">
    @Html.RouteLink("C#", 
        "category_topic", 
        new { 
            controller = "Home", 
            action = "Index", 
            topicId = "CSHARP",
            categoryId = ViewBag.CurrentCategoryId 
        }, 
        new{ @class="nav-link text-dark" })
</li>
<li class="nav-item">
    @Html.RouteLink("JavaScript", 
        "category_topic", 
        new { 
            controller = "Home", 
            action = "Index", 
            topicId = "JS",
            categoryId = ViewBag.CurrentCategoryId 
        }, 
        new{ @class="nav-link text-dark" })
</li>

3. 路由说明

现有路由配置中已包含category_topic和topic_category两个多参数路由,当生成的链接包含两个参数时,路由系统会自动匹配对应的路由规则,生成符合预期的URL格式。

内容的提问来源于stack exchange,提问作者Affan Sheikh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 11:52:47