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

如何使用Html.PagedListPager保留URL中的参数?

解决Html.PagedListPager点击页码丢失URL参数的问题

嘿,我完全懂你碰到的这个困扰!Html.PagedListPager默认不会自动帮你保留现有的URL查询参数,所以点击分页按钮时,Category和Brand这类参数就会被清空。不过别担心,只要手动把这些参数传递给分页链接的路由值就行,下面给你几种实用的解决方案:

方法1:手动构建路由值对象(最直接)

你可以在视图里直接通过Request.QueryString获取当前的参数,然后在生成分页链接时把它们加进去:

@Html.PagedListPager(Model, page => Url.Action("你的Action名称", new {
    page = page,
    Category = Request.QueryString["Category"],
    Brand = Request.QueryString["Brand"]
}))

如果你的ViewModel里已经包含了Category和Brand这两个属性(推荐这种方式,更安全),直接用模型属性代替Request.QueryString会更好:

@Html.PagedListPager(Model, page => Url.Action("你的Action名称", new {
    page = page,
    Category = Model.Category,
    Brand = Model.Brand
}))

方法2:构建完整的RouteValueDictionary(适合参数较多的场景)

如果URL里的参数不止这两个,你可以先把所有现有路由和查询参数都塞进RouteValueDictionary,再覆盖page参数:

@{
    var routeParams = new RouteValueDictionary(ViewContext.RouteData.Values);
    // 把所有查询参数添加进去
    foreach (string key in Request.QueryString.Keys)
    {
        routeParams[key] = Request.QueryString[key];
    }
    // 确保page参数会被分页链接的页码替换
    routeParams["page"] = Model.PageNumber;
}

@Html.PagedListPager(Model, page => Url.Action("你的Action名称", routeParams))

方法3:使用PagedListRenderOptions配置路由参数

还可以通过PagedListRenderOptions的RouteValueDictionary属性来传递参数,写法更规整:

@Html.PagedListPager(
    Model,
    page => Url.Action("你的Action名称"),
    new PagedListRenderOptions
    {
        RouteValueDictionary = new RouteValueDictionary
        {
            { "Category", Request.QueryString["Category"] },
            { "Brand", Request.QueryString["Brand"] }
        }
    }
)

注意事项

别忘了确保你的Controller Action方法能接收这两个参数,比如:

public ActionResult ProductList(int? page, string Category, string Brand)
{
    // 这里用Category和Brand过滤数据,再进行分页处理
    var products = // 你的数据查询逻辑
    int pageSize = 10;
    int pageNumber = (page ?? 1);
    return View(products.ToPagedList(pageNumber, pageSize));
}

这样处理之后,点击分页按钮时,Category和Brand参数就会被保留在URL里啦!

内容的提问来源于stack exchange,提问作者Arif YILMAZ

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:24:05