mehmetserif
mehmetserif

Reputation: 1227

MVC 3 Custom Url Routing

I want to create a custom route, as a default mvc creates route like this:

domain.com/deals/detail/5

but in my case i want to create a custom route for it:

domain.com/delicious-food-in-paris

so it has to look for deals controller's detail action with passing an id value 5 to it.

how can i do it?

Thanks

Upvotes: 1

Views: 1532

Answers (2)

Jan
Jan

Reputation: 16042

This route maps all one segment urls to the detail method of the deals controller and passes one string argument called dealName to it:

routes.MapRoute(
        null,
        "{dealName}",
        new { controller = "deals", action = "detail" }            
    );

But as AdamD have said, you should register that route as the last route in your setup because it will catch all urls which have only one segment.

With this approach you have to lookup your deal by name which might be not acceptable. So many apps use a hybrid approach and include the name and the id in the url like this:

domain.com/deals/5-HereComesTheLongName

Then you can use a route like this to get the id and optionally the name:

routes.MapRoute(
        null,
        "{id}-{dealName}",
        new { 
          controller = "deals", 
          action = "detail", 
          dealName = UrlParameter.Optional
        }
    );

Upvotes: 1

AdamV
AdamV

Reputation: 594

You can do this by defining a custom route in the Global.asax RegisterRoutes function. You would need to add this route after the default route so if the default controller action id pattern fails it will try to execute the final route.

An example would be to use the following:

        routes.MapRoute(
            "RouteName",
            "/{uri}", //this is www.domain.com/{uri}
            new { controller = "Controller", action = "ByUri" },
            new { uri = @"[a-z\-0-9]+" } //parameter regex can be tailored here
        );

After you register this route you can add a new custom controller to handle these routes, add the action that will handle this and accept a string as the parameter.

In this new action you can have a database lookup or some hardcoded valide routes that return Views.

Upvotes: 0

Related Questions