开发者

ASP.net mvc 2 routing

class HomeController
{
    public ActionResult Search(int[] sections, int categories)
    {
       return View();
    }
}

i need url like

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

What route map should i u开发者_如何学编程se?

At present RegisterRoutes looks

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 } 
            );
}


use something like:

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

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

to build the commaseparated string, and pass it in the route "Search/{csv}/{somevalue}"


I'd change the controller definition to handle the array:

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

then you can define the routing as usual: Home/{sections}/{categories}:

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

Notice that you have to add this on top of the default one.


Add search route, don't replace default one

Since you'll probably still be using default route with controller/action combination I suggest you do this:

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 } 
      );
}

But since it's hard to tell what requirements you're after here, maybe you're trying to use catch-all route parameter but not at the end of your URL request. If that's the case, you can check my code in blog post of such Route class that allows catch-all section anywhere in the URL and not just at the end as it is by default.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜