views:

58

answers:

1

I'm creating a HtmlHelper extention that should create a set of links pointing to the current URL, but that have a different language code as their first parameter. The languagecodes are passed in as a list.

Currently I require the UrlHelper to be passed in and do the following:

/*Warning: HACK*/
RouteValueDictionary vals = html.ViewContext.RouteData.Values;
vals["siteLanguage"] = "replaceMe";
string siteLanUrl = url.RouteUrl(vals).Replace("replaceMe", "{0}");
/*ENDHACK*/

Then I do a string replace so the "{0}" can be replaced with the set of language codes I have.

This is off course but ugly for a multitude of reasons. But I don't know how else I can generate these urls from with the HtmlHelper. Any suggestions?

+1  A: 

I'd create a helper for this...

public static string LanguageLink(this HtmlHelper html, string text, string languageCode)
{
    var routeValues = new RouteValueDictionary(html.ViewContext.RouteData.Values);
    routeValues["languageCode"] = languageCode;

    string action = routeValues["action"].ToString();
    return html.ActionLink(text, action, routeValues);
}

.. then in your master page (or wherever)...

 <%= Html.LanguageLink("English", "en") %> 
 <%= Html.LanguageLink("Spanish", "es") %> 
 <%= Html.LanguageLink("German", "de") %> 
 <%= Html.LanguageLink("French", "fr") %>

These will link to the same controller/action & route values but will add the language code. To get these to generate a friendly URL, you can add this above the default route.

 routes.MapRoute(
     "languageRoute",                                       
     "{languageCode}/{controller}/{action}/{id}",           
     new { controller = "Home", action = "Index", id = "" },
     new { languageCode = @"\w{2}" }
 );

(With this route, you wouldn't be able to match any controllers with a name of 2 characters, but that's probably fine).

Ben Scheirman