views:

245

answers:

3

We are working with an asp.net mvc app that is shared by multiple clients. We need the urls to include the clients url friendly name. For example:

domain.com/clientName/controller/action/id

This below appears to be working when it comes to routing, but the "clientName" is not generated correctly for the action link helpers.

_routes.MapRoute("DefaultRoute",
                "{clientName}/{controller}/{action}/{id}",
                new { controller = "Home", action = "Index", id = string.Empty },
                new { clientName = @"[\w-]+" });

We would like to continue using the Html.ActionLink Helper methods, but it does not include the clientName in the generated link. Do we have to write our own helpers in this scenario or is there an alternative approach?

Has anyone else built an application with this type of routing scenario? Any suggestions would be appreciated!

+3  A: 

You need to specify route values:

<%= Html.ActionLink("some text", "action", new { clientName = "someclient" })%>

Will generate:

http://host/someclient/Home/action

You could also specify a default value when declaring the route:

_routes.MapRoute("DefaultRoute",
    "{clientName}/{controller}/{action}/{id}",
    new { 
        controller = "Home", 
        action = "Index", 
        id = string.Empty, 
        clientName = "defaultClient" },
    new { clientName = @"[\w-]+" });
Darin Dimitrov
+2  A: 

It's been my experience that the ActionLink method referenced by Darin will generate a URL like:

http://host/Home/action?clientName=someClient

If you want to generate the URL exactly as you specified. Check out the RouteLink method that lets you specify the name of the Route you are matching:

<%= Html.RouteLink("some text", "DefaultRoute", new { clientName = "someclient" })%>
Bryan
@Bryan, I've tested the code I provided and it generated the expected url. Maybe in your case you put the routes declaration in the wrong order and it was the catch-all route that was executed. Specific routes should be put before the catch-all route.
Darin Dimitrov
good tip - thanks darin.
Bryan
A: 

What you are trying to do should work without having to use RouteLink or specifying an anonymous object. Make sure your route registrations are correct. For example, if you have something like:

routes.MapRoute("Base", 
                string.Empty,
                new { controller = "Home", 
                action = "Index", 
                id = string.Empty });

before your DefaultRoute, it can cause calls to ActionLink to return strange results. I've been burned by this before.

Page Brooks