Thad
Thad

Reputation: 1530

MVC Custom Routes and ActionLinks

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!

Upvotes: 5

Views: 5741

Answers (3)

Page
Page

Reputation: 10005

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.

Upvotes: 0

Bryan
Bryan

Reputation: 535

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" })%>

Upvotes: 11

Darin Dimitrov
Darin Dimitrov

Reputation: 1039508

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-]+" });

Upvotes: 7

Related Questions