Howto automatically add a specific value from current route to all generated links?

岁酱吖の 提交于 2019-12-18 17:13:27

问题


I have site culture in URLs like this:

routes.MapRoute(
    "Default", 
    "{language}/{controller}/{action}/{id}", 
    languageDefaults, 
    languageConstraints)

And it works like a charm with a little help from custom MvcHttpHandler that sets current thread's UI culture on every request based on route value. My problem is how do I automatically add the language route value from current request to all outgoing links? E.g. when page /EN/Foo/Bar is requested, I would like this

<%=Html.ActionLink(
    "example link", 
    MVC.Home.Index()) %>

To automatically generate the same result as this:

<%=Html.ActionLink(
    "example link", 
    MVC.Home.Index()
        .AddRouteValue(
            "language", 
            this.ViewContext.RouteData.Values["language"]) %>

And of course the same for all other helpers like BeginForm() etc. In my current code base there are already > 1000 occasions where these helpers are used, and requiring .AddRouteValue every time is very fragile as some developer will forget to use it with 100 % certainty.

I hope the only solution is not creating custom Html helpers for everything?


回答1:


It should preserve all values defined in route and present in RouteData automatically, unless you set it to something else. Try to create link without T4MVC or check your route definitions. Something like this works for me just fine:

routes.MapRoute("Default with language", "{lang}/{controller}/{action}/{id}", new
{
    controller = "Home",
    action = "Index",
    id = UrlParameter.Optional,
}, new { lang = "de|fr" });
routes.MapRoute("Default", "{controller}/{action}/{id}", new
{
    controller = "Home",
    action = "Index",
    id = UrlParameter.Optional,
    lang = "en",
});

+

protected void Application_AcquireRequestState(object sender, EventArgs e)
{
    MvcHandler handler = Context.Handler as MvcHandler;
    if (handler == null)
        return;

    string lang = (string)handler.RequestContext.RouteData.Values["lang"];

    CultureInfo culture = CultureInfo.GetCultureInfo(lang);

    Thread.CurrentThread.CurrentUICulture = culture;
    Thread.CurrentThread.CurrentCulture = culture;
}

+

<%: Html.ActionLink("About us", "Detail", "Articles", new { @type = ArticleType.About }, null) %>


来源:https://stackoverflow.com/questions/5060346/howto-automatically-add-a-specific-value-from-current-route-to-all-generated-lin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!