tags:

views:

28

answers:

2

Hi There,

Is there a way within asp.net MVC 2 whereby I can route a request and have a portion of the URL ignored and passed to the controller as a variable?

My needs state that I must store pages dynamically in a database, and they should be accessible by looking at the URL and reading the URL segments to find the relevant page. Effectively, I need a Site controller, to which the remaining portion of the URL will be passed.

Site-Controller/this/is/a/page

So this in case the site controller would pick up the /this/is/a/page 'string'

Is this possible?

Thanks!

+3  A: 

Yes, use a wildcard route, like:

        routes.MapRoute(
            "SiteController",                                        // Route name
            "Site-Controller/{*url}",                               // URL with parameters
            new { controller = "SiteController", action = "Index" }, // Parameter defaults
            null                                                     // constraints
        );

Then your action looks like:

public ActionResult Index(string url)
{
}
Craig Stuntz
+2  A: 

Create a wildcard Route in Global.asax which captures everything after the first segment of the url and passes it to your Action method:

routes.MapRoute("Page", 
                "Site-Controller/{*urlsegments}",
                new { 
                  controller = "Site-Controller",
                  action = "YourAction",
                  folders = ""
                });

Make sure your Action method accepts a 'urlsegments' parameter and you can work with it from there:

public ActionResult YourAction(string urlsegments)
{
    // Do something with the segments here
}
Mark B
both near identical answers that came in at the same time. I feel bad that I cant both give you credit for the right answer!
Sergio
Haha... well I voted Craig's answer up so hopefully that balances it out a bit! Glad it helped.
Mark B