Reputation: 13713
I'm building a small ASP.NET MVC website that is multilingual, but uses the same code base. I have a class that accepts xPath string and read from the appropriate language xml file.
To set the language I've defined the following route:
routes.MapRoute(
name: "Multilingual",
url: "{controller}/{language}/{action}/{id}",
defaults: new { controller = "Home", language = "en", action = "Index", id = UrlParameter.Optional }
);
and now I want to write an extension method for Html that will accept a path string and return the value.
public static class LanguageLiteralExtension
{
public static string LanguageLiteral(this HtmlHelper helper, string xPath)
{
}
}
inside that extension method I would like to get the language parameter defined in the route.
Is there any way to those parameters? I know that inside the controller I can get them as the parameters in the action method - but that's not what I want in this case - I would like to have it inside a class that has nothing to do with the controller.
Thanks
Upvotes: 2
Views: 2186
Reputation: 6839
You can still access everything from the request context in the helper, and has no need to pass the path as parameter, just grab it from the route data!
The easiest way:
public static class LanguageLiteralExtension
{
public static string LanguageLiteral(this HtmlHelper helper)
{
return helper.ViewContext.RequestContext.RouteData.Values["language"].ToString();
}
}
Don't forget to add the namespace to the Web.config at the View folder, then you don't need to import the namespace everywhere you want to use it.
Upvotes: 4