我正在使用以下路由来处理我的ASP.NET MVC应用程序的本地化
routes.MapRoute("Globalization", "{culture}/{controller}/{action}/{id}",
new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional
});
因此该方案为http://mysite.com/en-US/Contact或http://mysite.com/es-ES/Contact
我正在尝试在_Layout.cshtml中创建一些文化链接以切换文化。但我只需要转换文化并保持相同的观点。
当前视图:http://mysite.com/en-US/Contact
=>切换到es-ES
新视图:http://mysite.com/es-ES/Contact
我该怎么做?
感谢。
答案 0 :(得分:1)
实际上这很棘手。您可以简单地使用@Html.ActionLink("Spanish", null, new { @culture = "es-ES" })
,但这只会保留路由中定义的参数,查询字符串将在本地化版本中丢失。因此,我写了以下帮助:
/// <summary>
/// Returns current url modified by parameters
/// </summary>
/// <param name="context">Relevant request context</param>
/// <param name="withRouteValues">Values to add or override</param>
/// <param name="withoutRouteValues">Values to remove if present</param>
/// <returns>Url</returns>
public static RouteValueDictionary Current(RequestContext context, RouteValueDictionary withRouteValues = null, string[] withoutRouteValues = null)
{
var with = withRouteValues ?? new RouteValueDictionary();
var without = withoutRouteValues ?? new string[0];
var result = new RouteValueDictionary();
var queryString = context.HttpContext.Request.QueryString;
foreach (var key in queryString.AllKeys.Where(k => !IgnoreValues.Contains(k) && !without.Contains(k)))
result[key] = queryString[key];
var routeValues = context.RouteData.Values;
foreach (var pair in routeValues.Where(p => !IgnoreValues.Contains(p.Key) && !without.Contains(p.Key)))
result[pair.Key] = pair.Value;
foreach (var pair in with.Where(p => !IgnoreValues.Contains(p.Key) && !without.Contains(p.Key)))
result[pair.Key] = pair.Value;
return result;
}
/// <summary>
/// Returns anchor element with current url modified by parameters
/// </summary>
/// <param name="self">Html helper</param>
/// <param name="linkText">The inner text of anchor element</param>
/// <param name="withRouteValues">Values to add or override</param>
/// <param name="withoutRouteValues">Values to remove if present</param>
/// <returns>Anchor element</returns>
public static MvcHtmlString CurrentLink(this HtmlHelper self, string linkText, object withRouteValues = null, string[] withoutRouteValues = null)
{
var routeValues = Current(self.ViewContext.RequestContext, withRouteValues, withoutRouteValues);
return self.ActionLink(linkText, null, routeValues);
}
这个@Html.CurrentLink("Spanish", new { culture = "es-ES" })
应该完全符合你的要求。