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

MVC C# PagedListPager如何传递int数组参数?

解决MVC C# PagedListPager中传递int数组的问题

我来帮你搞定这个问题——你看到的System.Int32[]是因为ASP.NET MVC默认不会自动把数组解析成正确的查询字符串格式,直接把数组对象传给Url.Action的路由参数时,会调用数组的ToString()方法,所以才出现了这个奇怪的结果。下面给你几个可行的解决方案:

方法一:手动构造数组的查询字符串片段

通过string.Join把数组转换成多个同名的查询参数(比如codOccu=1&codOccu=2),再和其他参数拼接成完整URL:

@{
    // 将int数组转为查询字符串片段
    var codOccuQuery = ViewBag.codOccu != null 
        ? string.Join("&", ((int[])ViewBag.codOccu).Select(id => $"codOccu={id}")) 
        : string.Empty;
    
    // 生成基础URL(包含除数组外的其他参数)
    var baseUrl = Url.Action("Index", new { 
        pagina, 
        nomeEmp = ViewBag.Empresas, 
        dtAbert = ViewBag.DataIni, 
        dtFinal = ViewBag.DataFim, 
        codStatus = ViewBag.codStatus, 
        codUsu = ViewBag.CodUsu, 
        codSet = ViewBag.CodSet, 
        order = ViewBag.order 
    });
    
    // 拼接数组参数到基础URL
    var fullUrl = string.IsNullOrEmpty(codOccuQuery) 
        ? baseUrl 
        : $"{baseUrl}&{codOccuQuery}";
}

@Html.PagedListPager(Model, pagina => fullUrl)

方法二:使用RouteValueDictionary传递数组

RouteValueDictionary可以正确处理数组参数,自动生成多个同名的查询键值对:

@Html.PagedListPager(Model, pagina => {
    var routeValues = new RouteValueDictionary {
        { "pagina", pagina },
        { "nomeEmp", ViewBag.Empresas },
        { "dtAbert", ViewBag.DataIni },
        { "dtFinal", ViewBag.DataFim },
        { "codStatus", ViewBag.codStatus },
        { "codUsu", ViewBag.CodUsu },
        { "codSet", ViewBag.CodSet },
        { "order", ViewBag.order }
    };

    // 遍历数组,逐个添加到路由参数中
    if (ViewBag.codOccu != null)
    {
        foreach (var id in (int[])ViewBag.codOccu)
        {
            routeValues.Add("codOccu", id);
        }
    }

    return Url.Action("Index", routeValues);
})

关键:确保Action方法能正确接收数组

无论用哪种方法,都要确保你的Index Action方法的参数定义为int[] codOccu,这样ASP.NET MVC的模型绑定器才能正确把多个codOccu查询参数绑定到数组上:

public ActionResult Index(int pagina, int[] codOccu, /* 其他参数 */)
{
    // 业务逻辑处理
    return View();
}

这两种方法都会生成类似http://localhost:8080/Atendimento?pagina=2&codOccu=1&codOccu=2&codStatus=...的正确查询字符串,ASP.NET MVC会自动把这些同名参数绑定到你的int数组中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:04:54