I'm using the following route to handle localization on my ASP.NET MVC Application
routes.MapRoute("Globalization", "{culture}/{controller}/{action}/{id}",
new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional
});
So the scheme is http://mysite.com/en-US/Contact or http://mysite.com/es-ES/Contact
I'm trying to make some culture links in _Layout.cshtml in order to switch culture. But i need to only switch culture and stay on the same view.
Current View : http://mysite.com/en-US/Conta开发者_开发技巧ct
=> Switch To es-ES
New View : http://mysite.com/es-ES/Contact
How can i perform that ?
Thanks.
This is quite tricky actually. You could simply use @Html.ActionLink("Spanish", null, new { @culture = "es-ES" })
, however this will preserve only parameters defined in route and query string will be lost in localized version. Because of this I've written following helper:
/// <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);
}
With this @Html.CurrentLink("Spanish", new { culture = "es-ES" })
should accomplish exactly what you want.
精彩评论