Monday, July 16, 2012

routes.MapRoute

In Ruby on Rails, we define request route on config/route.rb as DSL like this:
match ':controller(/:action(/:id))(.:format)'

I learned from the book Programming Microsoft® ASP.NET MVC, Second Edition that we define request route (1) on Global.asax as RegisterRoutes method or (2) on XXXXAreaRegistration.cs as RegisterArea method, in ASP.NEt MVC. This is the sample:
public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}" // URL with parameters
    );
}

If we want to set default value for route, add anonymous object as 3rd parameter:
public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Default value for parameters
    );
}
In this sample, UrlParameter.Optional means the rest of parameters.

And then, if we want to set constraint for route, add anonymous object as 4th parameter:
public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Default value for parameters
        new { id = @"\d{8}" } // Constraint for parameters
    );
}

No comments:

Post a Comment