MVC小白 - 改变URL的一部分,一个链接 [英] MVC noob - changing part of URL in a link
问题描述
我有支持本地化的网站。我希望能够英语和法语之间切换。
I have a site that supports localization. I would like to be able to switch between english and french.
让说,用户当前网址:
http://www.mysite.com/ 连接 /首页
Let say the user is currently at URL: http://www.mysite.com/en/Home
我想重定向到:
http://www.mysite.com/ FR /首页
I would like to redirect to: http://www.mysite.com/fr/Home
如果在法国的链接,用户点击如何将URL部分更改为FR尚未更改URL(基本上我想preserve用户的当前位置)的家的一部分
If the user click on a "French" link how to change the URL part to "fr" yet not change the "Home" part of the URL (basically I want preserve the current location of the user)
希望我的问题是有道理的!我可能失去了一些东西非常基本的?
Hope my question makes sense! I'm probably missing something very basic?
编辑:类找到了解决办法。
Kind of found a solution.
<%= 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的动作/控制器。也许有一个更清洁的解决方案?
This maintains the action/controller of the current URL. Maybe there's a cleaner solution?
推荐答案
在您的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}" });
你可以访问的变量语言的语言在你的控制器
And you can have access to the language with the variable language in your controller
要生成链接:
<%= Html.ActionLink("French", ViewContext.RouteData.Values["action"], new { language = "fr" }) %>
和你可以做一个基类控制器与此属性:
And you can make a base class controller with this property:
public string Language { get { return this.Routedata["language"]; } }
这篇关于MVC小白 - 改变URL的一部分,一个链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!