views:

135

answers:

0

Hi all,

I am new to asp.net mvc, so please bear with me.

We have the following route dictionary setup.

routes.MapRoute(
            "Default",                                              // Route name
            "{language}/{controller}/{action}/{id}",                           // URL with parameters
            new { language = "en", controller = "Home", action = "Index", id = "" }  // Parameter defaults
        );

for any given page in our app, we to render a link to the a french version of the same page. For example, the page:

http://www.example.com/en/home

should have link on that page that points to

http://www.example.com/fr/home

Now I have the following UrlHelper extension method

public static string FilpLanguage(this UrlHelper urlHelper)
    {
        var data = urlHelper.RequestContext.RouteData;
        if (System.Threading.Thread.CurrentThread.CurrentCulture == CultureInfo.GetCultureInfoByIetfLanguageTag("en-CA"))
            data.Values["language"] = "fr";
        else
            data.Values["language"] = "en";

        return urlHelper.RouteUrl(data.Values.Where(item => item.Value != null));
    }

However, calling FilpLanguage on www.example.com/en/home will return the following URL:

www.example.com/en/home?current=[,]

Am I missing something here? where did the current parameter come from?

Thanks in advance.

Update

I found out that I can simply use the RouteValueDictionary in the current request context

public static MvcHtmlString GetOtherLanguageLink(this HtmlHelper html, string linkText)
    {
        var routeDictionary = html.ViewContext.RouteData.Values;

        if (null == routeDictionary["action"] || !(routeDictionary["action"] is string) ||
            null == routeDictionary["controller"] || !(routeDictionary["controller"] is string))
            throw new ArgumentException("Either action or controller is missing in routeData.Values (RouteValueDictionary)");

        if (System.Threading.Thread.CurrentThread.CurrentCulture == CultureInfo.GetCultureInfoByIetfLanguageTag("en-CA"))
            routeDictionary["language"] = "fr";
        else
            routeDictionary["language"] = "en";

        // add query strings as extra route values
        foreach (string key in html.ViewContext.RequestContext.HttpContext.Request.QueryString.AllKeys)
            if (!string.IsNullOrEmpty(key) && !routeDictionary.ContainsKey(key))
                routeDictionary.Add(key, html.ViewContext.RequestContext.HttpContext.Request.QueryString[key]);

        return html.ActionLink(linkText, routeDictionary["action"].ToString(), routeDictionary["controller"].ToString(), routeDictionary, null);
    }