【问题标题】:Howto automatically add a specific value from current route to all generated links?如何自动将当前路由中的特定值添加到所有生成的链接?
【发布时间】:2011-06-30 22:16:12
【问题描述】:

我的网址中有这样的网站文化:

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

在自定义 MvcHttpHandler 的帮助下,它就像一个魅力,它根据路由值在每个请求上设置当前线程的 UI 文化。我的问题是如何自动将当前请求中的语言路由值添加到所有传出链接?例如。当页面 /EN/Foo/Bar 被请求时,我想要这个

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

要自动生成与此相同的结果:

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

当然,对于 BeginForm() 等所有其他帮助程序也是如此。在我当前的代码库中,已经有超过 1000 次使用这些帮助程序,并且每次都需要 .AddRouteValue 非常脆弱,因为一些开发人员会忘记100% 肯定地使用它。

我希望唯一的解决方案不是为所有内容创建自定义 Html 助手?

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-mvc-2 asp.net-mvc-routing


    【解决方案1】:

    它应该自动保留在路由中定义并出现在RouteData 中的所有值,除非您将其设置为其他值。尝试在没有 T4MVC 的情况下创建链接或检查您的路由定义。像这样的东西对我来说很好:

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

    【讨论】:

    • 奇怪,非常奇怪:这是我期望它工作的方式,但它没有。现在我创建了一个香草测试项目,你是对的,它真的像你写的那样工作。我的项目中一定有什么东西破坏了这种行为(第一个嫌疑人是 T4MVC)。
    • T4MVC 不是原因,而是一个纯粹而简单的错误:我在母版页上有语言更改链接。在渲染这些链接时,可用语言的列表被循环通过,并且在循环期间当前路线被错误地改变了。
    猜你喜欢
    • 2011-09-25
    • 1970-01-01
    • 1970-01-01
    • 2015-11-28
    • 2018-11-10
    • 2017-06-09
    • 2010-11-17
    • 1970-01-01
    • 2021-12-04
    相关资源
    最近更新 更多