2

I know I can change the routing in the RouteConfig in my MVC application:

routes.MapRoute(name: "epage", url: "view/SpecificURL", defaults: new {
    controller = "ePage",
    action = "Index"
})

but I am wondering how to redirect for values comming from a db. There is one row in my db that has titles . So for each title comming from the db I want to redirect to a specific url ex.

the title in db may be "pink" I want www.mydomain.com/pink to be rerouted to a specific url . The URL that I want it redirected to is also in the db. I looked at lots of questions on this and can not seem to find any that dynamically change the routing of urls

Scott Selby
  • 9,420
  • 12
  • 57
  • 96
  • Why do you need to redirect it to a specific URL? Couldn't you do a lookup for "pink" in your database and have it simply return the appropriate content? – John Koerner Jan 17 '13 at 02:54
  • I know this isn't the same question but it seems like you are looking for the same thing: http://stackoverflow.com/questions/13971468/depth-first-nested-routing-in-an-asp-net-website/13980352 What you want to do is create your own route handler. – cheesemacfly Jan 17 '13 at 03:18

1 Answers1

0

You can setup a route like this:

routes.MapRoute(name: "Default",
    url: "{id}",
    defaults: new { controller = "Home", action = "Index" });

Then in your controller (the HomeController in my case):

public ActionResult Index(string id)
{
    ContentResult cr = new ContentResult();
    // Do a DB lookup here to get the data you need from the database to generate the appropriate content.
    cr.Content = id;
    return cr;
}

This example simply returns the string that was sent. So now if I browse to http://localhost/mysite/pink I would get "pink" back as my result. You could easily use this method to then do a lookup to your custom database to determine the correct content to return.

If your existing routes don't let you take this route :), then you can always do a SQL query in the RegisterRoutes method and populate the route table from that.

John Koerner
  • 37,428
  • 8
  • 84
  • 134
  • The problem with url: "{id}", is that will ignore all my other controllers – Scott Selby Jan 17 '13 at 03:06
  • Some of it depends on how you have your routes setup. I have the route listed plus `routes.MapRoute( name: "Base", url: "{controller}/{action}");` and it returns the string if I only put in a single param, but if I put in a controller & action, I get that route. – John Koerner Jan 17 '13 at 03:13