How to get the url to the current action (after modifying some route data)?
I'm localising a site via a Change Language control in the master page. I need to r开发者_JS百科ender the control with the current url you're on in each of the different languages.
So if you're on http://site.com/en/Home/About and you change the language to french, I need to direct you to http://site.com/fr/Home/About.
The localisation code works on the route data language property, so I've been trying to figure out how I can:
- Get access to the current action (with all original parameters)
- Get the url to the current action (with all original parameters) with the route data changed.
Can anyone point me in the right direction?
I've tried passing the ViewContext from the parent into the UserControl, which gives me access to the route data but I can't figure out how to get the language routed url from that.
I ran this on the site I'm working on locally and it seemed to work. There's probably a cleaner way.
HttpRequestBase hrb = HttpContext.Request;
System.Uri url = hrb.Url;
string[] test = url.AbsoluteUri.Split('/');
int nIndex = 0, nCounter = 0;
foreach(string str in test)
{
if (str.Contains("site.com"))
{
nIndex = nCounter;
break;
}
nCounter++;
}
string strLanguage = test[nIndex + 1];
Obviously the +1 can even go in the IF statement, but I didn't think it looked good there. Hope this helps some.
I'm not 100% happy with this, I haven't got to a stage where I can fully test the impact of this but this is what I'm going for so far. Please do answer if you have a better solution.
I pass the ViewContext from the masterpage so I get the ViewContext with route data from whatever url you're currently on.
private string GetLocalisedUrl(ViewContext viewContext, string language)
{
viewContext.RouteData.DataTokens[LANGUAGE_ROUTEDATA_KEY] = language;
UrlHelper helper = new UrlHelper(viewContext.RequestContext);
return helper.Action(viewContext.RouteData.Values["action"].ToString(), viewContext.RouteData.Values["controller"].ToString(), viewContext.RouteData.DataTokens);
}
精彩评论