【问题标题】:Map Routes for Pagination in MVC在 MVC 中为分页映射路由
【发布时间】:2011-05-29 09:13:25
【问题描述】:

我正在使用一个与 NerdDinner 示例中使用的非常相似的分页类。分页方面工作正常,但我正在努力让所有路线正常工作。

目前我们有一组MapRoute

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}/{page}", // URL with parameters
            new
            {
                controller = "Home",
                action = "Index",
                id = UrlParameter.Optional,
                page = UrlParameter.Optional
            } // Parameter defaults
        );

我们希望 URL 是 /mycontroller/myaction/1/page5,而不是 /mycontroller/myaction/1/5,这样对用户来说更有意义。我暂时找不到办法。

其次,我们如何设置路线,以便动作也可以与分页一起使用。 IE。 /controller/page1 而不是 /controller/index/page1

【问题讨论】:

  • 使用"{controller}/{action}/{id}/page{page}" 将使您的网址看起来像/mycontroller/myaction/1/page5。关于您的第二个问题,您能否详细说明how do we set up the routes so that actions can used with pagination too 的含义?

标签: c# asp.net-mvc pagination


【解决方案1】:

你应该有两条路线:

首先用于分页(将使用默认控制器和操作):

    routes.MapRoute(
        "Default", // Route name
        "home/{id}/{page}", // URL with parameters
        new
        {
            controller = "Home",
            action = "Index",
            id = UrlParameter.Optional,
            page = UrlParameter.Optional
        } // Parameter defaults
    );

所有控制器的最后一条路线:

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}/{page}", // URL with parameters
        new
        {
            controller = "Home",
            action = "Index",
            id = UrlParameter.Optional,
            page = UrlParameter.Optional
        } // Parameter defaults
    );

因此,上面的路由 /home/1/page5 将由主控制器索引操作处理, 但 someController/someAction/1/page5 通过第二条路线。

你应该知道,首先你需要放置处理更少 url 的路由,而不是普通路由,比如上面所有控制器的第二条路由。

在控制器动作中你也可以像这样回顾路由参数:

string page = RouteData.Values["page"];

所以对于上面示例页面中的 url home/1/page5 将等于“page5”,您可以解析此字符串以获得页码。

对于我来说,我使用以下方法从路由数据、帖子正文、查询字符串中获取参数:

 protected T GetQueryParam<T>(String name, T defValue = default(T))
        {
            String param = HttpContext.Request.QueryString.Get(name);
            if (String.IsNullOrEmpty(param))
                param = HttpContext.Request.Params[name];
            if ( String.IsNullOrEmpty(param))
                param = (String) RouteData.Values[name] ?? String.Empty;

            if (String.IsNullOrEmpty(param) )
                return defValue;

            return (T)Convert.ChangeType(param, typeof(T));
        }

所以,如果您需要使用上述方法获取页面,您只需执行以下操作:

var page = GetQueryParam<string>("page");// in case if page parameter not exists default value for type will be returned

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-05
    • 1970-01-01
    • 1970-01-01
    • 2016-12-13
    • 1970-01-01
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多