HOWTO自动从当前路径特定值添加到所有生成的链接? [英] Howto automatically add a specific value from current route to all generated links?

查看:120
本文介绍了HOWTO自动从当前路径特定值添加到所有生成的链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网站的URL的文化是这样的:

I have site culture in URLs like this:

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

和它的工作方式与定制MvcHttpHandler一点点帮助,设置基于路径值每次请求当前线程的UI文化的魅力。我的问题是我怎么会自动从当前请求添加的语言路线值所有出站链接?例如。当请求页/ EN /美孚/酒吧,我想这

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"]) %>

当然,同样为所有其他佣工喜欢BeginForm()等。在我目前的code基已经有1000场合使用这些佣工,并要求.AddRouteValue每次都是因为一些开发商很脆弱会忘记有100%的把握使用它。

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.

我希望唯一的解决办法是不是一切创建自定义HTML佣工?

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

推荐答案

应该在的RouteData 的路线和present定义的所有值自动preserve,除非你把它设置为别的东西。尝试没有T4MVC创建链接或检查你的路由定义。像这样的东西为我工作就好了:

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) %>

这篇关于HOWTO自动从当前路径特定值添加到所有生成的链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆