Using EPiServer 8 and MVC, what would be the best way to generate a url (or anchor element) to another language branch of the current page, yet keeping all the querystring parameters and the current action of the controller?
ExampleSuppose you are athttp://localhost/products/view/?productid=foo, where products maps to a controller (and EPiServer page) and view is an action within that controller.
Now, by clicking a link, you want to go to the german version of the very same page:http://localhost/de/products/view/?productid=foo
How to achieve this? This is my current implementation that seems to work, but feels rather hackish:
var routeValues = Request.QueryString.ToRouteValues();
routeValues["language"] = "de";
if (ViewContext.RouteData.Values["action"] != null)
routeValues["action"] = ViewContext.RouteData.Values["action"];
@Html.ContentLink("German", Model.CurrentPage.ContentLink, routeValues, null)
(ToRouteValues() is just an extension method to convert a NameValueCollection to a RouteValueDictionary)
Maybe in your case that could be a bit overengineering, but you can take a look at how I implemented content language available everywhere, on every page in EPiServer - http://blog.tech-fellow.net/2015/04/09/switch-content-language-everywhere-in-episerver/.
Search for section "Preserving Query Parameters".
Interesting reading! Actually my scenario is also globalization and a general language switcher. Your take on preserving query parameters looks good, but it doesn't really handle preserving the current controller action, right?
Say we are at:
then you would only get this target url:
This is why I need to extract the action parameter from current RouteData.
Yes, you are right. I excplicitly avoided to replicate action. We usually do normal page rendering in Index action which is default one, and special action name is used mostly for posts - actions that are mutate (manipulate) state or data in the system. Here sometimes Http verb is not POST, but GET sometimes as well. Therefore - you may find yourself in cases where switching the language may result is double records in database or basically end up with the same action executed in different language.
But back to original question - your approach is correct. This is the way to extract action of the currently executing controller.