Create url from HtmlHelper

I am creating an extension HtmlHelper that should create a set of links pointing to the current url, but they have a different language code as the first parameter. Language codes are passed as a list.

Currently I need to pass UrlHelper 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 replace the string, so "{0}" can be replaced with the set of language codes I have.

It is, of course, but ugly for a variety of reasons. But I don't know how else I can generate these urls using HtmlHelper. Any suggestions?

0


a source to share


1 answer


I would 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 on the homepage (or wherever) ...

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

      



They will bind to the same controller / action and route values, but add language code. To get them to create 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}" }
 );

      

(You won't be able to match any two-character name controllers with this route, but that's probably fine.)

+1


a source







All Articles