views:

211

answers:

2

I just started using ASP.NET MVC and I have two routing questions.

  1. How do I set up the following routes in ASP.NET MVC?

    domain.com/about-us/
    domain.com/contact-us/
    domain.com/staff-bios/
    I don't want to have a controller specified in the actual url in order to keep the urls shorter. If the urls looked liked this:
    domain.com/company/about-us/
    domain.com/company/contact-us/
    domain.com/company/staff-bios/
    

    it would make more sense to me as I can add a CompanyController and have ActionResults setup for about-us, contact-us, staff-bios and return appropriate views. What am I missing?

  2. What purpose does the name "Default" name have in the default routing rule in Global.asax? Is it used for anything?

Thank you!

+2  A: 

I'll answer your second question first - the "Default" is just a name for the route. This can be used if you ever need to refer to a route by name, such as when you want to do URL generation from a route.

Now, for the URLs that you want to set up, you can bypass the controller parameter as long as you're ok with always specifying the same controller as a default. The route might simply look like this:

{action}/{page}

Make sure that it's declared after your other routes, because this will match a lot of URLs that you don't intend to, so you want the other routes to have a crack at it first. Set it up like so:

routes.MapRoute(null, "{action}/{page}", 
                 new { controller = "CompanyController", action = "Company", page = "contact-us" } );

Of course your action method "Company" in your MyDefault controller would need to have a "string page" parameter, but this should do the trick for you. Your Company method would simply check to see if the View existed for whatever the page parameter was, return a 404 if it didn't, or return the View if it did.

womp
A: 

Speaking of setting up routes and Phil Haack, I have found his Route Debugger to be invaluable. It's a great tool for when you don't understand why particular routes are being used in place of others or learning how to set up special routing scenarios (such as the one you've mentioned). It's helped clear up many of the intricacies of route creation for me more than any other resource.

Bit Destroyer