【问题标题】:ASP.net mvc 2 routingASP.net mvc 2 路由
【发布时间】:2011-08-05 07:08:18
【问题描述】:
class HomeController
{
    public ActionResult Search(int[] sections, int categories)
    {
       return View();
    }
}

我需要像这样的网址

website.com/search/1,2,3/5

我应该使用什么路线图?

目前RegisterRoutes看起来

public static void RegisterRoutes(RouteCollection routes)
{
      routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

      routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", 
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
            );
}

【问题讨论】:

    标签: asp.net asp.net-mvc-2 routing


    【解决方案1】:

    使用类似的东西:

    var ints = new int[] {1, 2, 3, 4, 5};
    

    var 结果 = string.Join(",", ints.Select(x => x.ToString()).ToArray());

    构建逗号分隔的字符串,并在路由“Search/{csv}/{somevalue}”中传递它

    【讨论】:

    • 您需要添加一个新的 routes.MapRoute 并将其放在默认的路由上以使其工作
    【解决方案2】:

    我会更改控制器定义来处理数组:

        public ActionResult Search(string sections, int categories)
    {
       // sectionsArray is int[].
       var sectionsArray = sections.Split(',').Select(x => int.Parse(x)).ToArray();
       return View();
    }  
    

    然后你可以像往常一样定义路由:Home/{sections}/{categories}

    routes.MapRoute(
        "Search", // Route name
        "{Home}/{sections}/{categories}", // URL with parameters
        new { controller = "Home", action = "Search" } // Parameter defaults
    );  
    

    请注意,您必须将其添加到默认设置之上。

    【讨论】:

    • @Robert:根据 mola10 的问题,我已将 home 作为控制器。他在class HomeController中定义了搜索方法
    • 我说的是这个 Home"{Home}/{sections}/{categories}",它将 home 设置为 URL 参数。
    【解决方案3】:

    添加搜索路径,不要替换默认路径

    由于您可能仍会使用带有控制器/动作组合的默认路由,我建议您这样做:

    public static void RegisterRoutes(RouteCollection routes)
    {
          routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
          routes.MapRoute(
                "Search",
                "search/{sections}/{section}", // rename these variables to what they actually are
                new { controller = "Search", action = "Sections", sections = UrlParameter.Optional, section = UrlParameter.Optinal } 
          );
    
          routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", 
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
          );
    }
    

    但是由于在这里很难说出您的要求是什么,也许您正在尝试使用包罗万象的路由参数,而不是在 URL 请求的末尾。如果是这种情况,您可以 check my code in blog post 此类 Route 类,它允许在 URL 中的任何位置而不是默认情况下仅在末尾处捕获所有部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多