how to prefix a culture string such as “en-gb” before the {controller} position in the url in asp.net mvc?
-
05-06-2021 - |
Question
so basically I want to achieve a multi-lingual website with the following scenarios:
- Using ASP.NET MVC 3
- most language are using resource files so they are using same views, however there are also many views that are country-specific (i.e. language culture specific) and not available for all.
- example url: http://localhost/en-us/{area}/{controller}/{action}/{id}
The MVC folder structure as here:
- Areas
- Channel1
- Controllers
- Content
- Views
- en-us
- View1.cshtml
- View2.cshtml
- zh-cn
- View1.cshtml
- View2.cshtml
<b>- Special.cshtml</b>
- Channel2
....(similar folder structure)
- ....
I think there must be a way to define the "en-us" into a parameter like {lang} and make decision in a default Controller outside the Areas - however I'm asp.net MVC newbie, how can I do that?
Solution
You can always write your own viewengine to look at folders based on what comes in. There's code out there for a ThemedViewengine that does just that.
OTHER TIPS
Here's a fantastic article with practical suggestions on how to implement globalization on ASP.NET MVC 3
There's no great way to do this, but it is possible. First, you need to rearrange your views a little bit -- they still have to have a controller. Let's say the files you have (View1.cshtml
and View2.cshtml
) live in your home controller. Put them here:
- Views
- Home
- en-us
- View1.cshtml
- View2.cshtml
- zh-cn
- View1.cshtml
- View2.cshtml
Then, create a custom route for the views in Global.asax.cs
:
routes.MapRoute(
"MultiLingual",
"{lang}/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", lang="en-us", id = UrlParameter.Optional }
);
Finally, in your home controller (or whatever controller you want to put the views in), use the lang
parameter to determine which view to use:
public ActionResult View1( string lang, int? id ) {
return View( lang + "/View1" );
}
public ActionResult View2( string lang, int? id ) {
return View( lang + "/View2" );
}
I tried this and it works, but it feels awfully clunky, and not very DRY (at least in the actions). Anyone have a better approach?