1

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

2
  • Where should the value 5 come from? There is no 5 in your sample url! Commented Jan 26, 2012 at 9:20
  • Well ok i can maybe look for the name not the id, i can pass the deal name as a parameter. Commented Jan 26, 2012 at 9:23

2 Answers 2

1

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
        }
    );
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.