Question

I have link for example domain.com/de/controler/action?param=value and I want make actionlink to keep same link just change de to en. If I am trying to get values with ViewContext.RouteData.Values["id"]; I getting null value. Any ideas?

@Html.ActionLink("New Language", 
  ViewContext.RouteData.GetRequiredString("action"),  
  ViewContext.RouteData.GetRequiredString("controller"),
  new { lang = "en" }                            
)
Était-ce utile?

La solution

You could write a custom url helper:

public static class UrlExtensions
{
    public static string LanguageUrl(this UrlHelper urlHelper, string lang)
    {
        var rd = urlHelper.RequestContext.RouteData;
        var request = urlHelper.RequestContext.HttpContext.Request;
        var values = new RouteValueDictionary(rd.Values);
        foreach (string key in request.QueryString.Keys)
        {
            values[key] = request.QueryString[key];
        }
        values["lang"] = lang;
        return urlHelper.RouteUrl(values);
    }
}

and then use it like this in the view:

<a href="@Url.LanguageUrl("en")">
    <img src="@Url.Content("~/content/flag_en.jpg")" alt="en" />
</a>

and you could of course write another helper to make the rendering of the entire anchor which would use our first helper:

public static class HtmlExtensions
{
    public static IHtmlString ChangeLanguage(this HtmlHelper htmlHelper, string lang, string imgUrl)
    {
        var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
        var anchor = new TagBuilder("a");
        anchor.Attributes["href"] = urlHelper.LanguageUrl(lang);
        var img = new TagBuilder("img");
        img.Attributes["alt"] = lang;
        img.Attributes["src"] = urlHelper.Content(imgUrl);
        anchor.InnerHtml = img.ToString(TagRenderMode.SelfClosing);
        return new HtmlString(anchor.ToString());
    }
}

and then:

@Html.ChangeLanguage("en", "~/content/flag_en.jpg")

Now if we suppose that you navigated to /de/home/index/123?param1=value1&param2=value2, then the @Html.ChangeLanguage("en", "~/content/flag_en.jpg") would have generated the following markup:

<a href="/en/home/index/123?param1=value1&amp;param2=value2">
    <img alt="en" src="/content/flag_en.jpg" />
</a>

Autres conseils

I think that you need an Controller Action "ChangeLanguage" in order to actually get the referrer URL and redirect.

Other option is that since the ActionLink is placed IN the view that need to be "translated", you can hardcode the Action and Controller.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top