gpt4 book ai didi

asp.net-mvc - MVC - 更改链接中 URL 的一部分

转载 作者:行者123 更新时间:2023-12-03 04:28:00 24 4
gpt4 key购买 nike

我有一个支持本地化的网站。我希望能够在英语和法语之间切换。

假设用户当前位于以下 URL: http://www.example.com/**en**/Home

我想重定向到: http://www.example.com/**fr**/Home

如果用户单击“法语”链接,如何将 URL 部分更改为“fr”,但不更改 URL 的“主页”部分(基本上我想保留用户的当前位置)

希望我的问题有意义!我可能错过了一些非常基本的东西?

编辑:找到了解决方案。

<%= Html.ActionLink("Français", ViewContext.RouteData.Values["action"].ToString(), ViewContext.RouteData.Values["controller"].ToString(), new { culture = "fr" }, null)%>
<%= Html.ActionLink("English", ViewContext.RouteData.Values["action"].ToString(), ViewContext.RouteData.Values["controller"].ToString(), new { culture = "en" }, null)%>

这会维护当前 URL 的操作/ Controller 。也许有更干净的解决方案?

最佳答案

在您的 Global.asax

 routes.MapRoute(
name: "LocalizedRoute",
url: "{language}/{controller}/{action}/{id}",
defaults:
new
{
language= "fr",
controller = "Home",
action = "Index",
id = UrlParameter.Optional
},
constraints: new { language= @"[a-z]{2}" });

并且您可以使用 Controller 中的变量语言访问该语言

生成链接:

<%= Html.ActionLink("French", ViewContext.RouteData.Values["action"], new { language = "fr" }) %>

您可以使用此属性创建一个基类 Controller :

public string Language { get { return this.Routedata["language"]; } }

关于asp.net-mvc - MVC - 更改链接中 URL 的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2603444/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com