Fria
Fria

Reputation: 119

Changing single route part of URL

I have the following route:

routes.MapRoute(
    "Default", // Route name
    "{language}/{controller}/{action}/{id}",
    new { language = "en", controller = "XY", id = UrlParameter.Optional } 
);

For changing the language of the site, I would like to create links, which correspond exactly to the url of the current page, but have another language part.

What would be the best way, to generate such a link?

Upvotes: 4

Views: 143

Answers (2)

Dismissile
Dismissile

Reputation: 33071

You could do something like this:

@Html.RouteLink("Switch Language", "Default", new { 
    controller = ViewContext.RouteData.Values["controller"], 
    action = ViewContext.RouteData.Values["action"], 
    id = ViewContext.RouteData.Values["id"], 
    language = "fr" 
})

It would probably make sense to make an extension method to handle this though.

Upvotes: 1

Nathan Taylor
Nathan Taylor

Reputation: 24606

Most likely, you'll want to insert the {language} value as part of each link-rendering View's ViewModel or ViewData. There's a few different way you could achieve this; such as overloading your controller's OnActionExecuted() method. If you take this approach, I suggest making all of your controllers inherit from a single base controller.

protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
    filterContext.Controller.ViewData["Language"] = GetUserLanguage();
    base.OnActionExecuted(filterContext);
}

And then in your View:

@Url.Action("Index", "Home", new { language = ViewData["Language"] })

Alternatively, you might consider overloading the Url.Action() and Html.ActionLink() methods with logic which appends this value automatically.

Upvotes: 2

Related Questions