Localizing ASP.NET MVC web application
As I mentioned in last post, using straight forward .NET localization feature will not buy us any benefits in as ASP.NET MVC application, the reasons again are:
- ASP.NET MVC web applications do not use server control, which will make us lose the advantage of localize controls implicitly.
- Resources can’t be used outside the web application (I am talking about the Global resources here)
So I did some search and I found some approaches and following is the one I liked the most.
- Create a new class library project in you solution which will have all resources (Global and/or Local) files needed.
- Add resource file to the project (i.e. Global.resx) and any other languages versions of this file.
- Open the properties window for that file (right click the file –> Properties); you will find this by default its Build Action is Embedded Resource.
- Change Custom Tool property to PublicResXFileCodeGenerator instead of ResXFileCodeGenerator, you can do that by opening the resource file in the editor and change the Access Modifier drop down list to Public.
- add your Custom Tool Namespace property to whatever namespace you like to use (i.e. MyResources)
- Include a reference for this project and enjoy the strongly typed resources objects (i.e. MyResources.Global.string1).
By having custom namespace you can build your own structure for resources files; (MyResources.Global, MyResources.Views.About, MyResources.ValidationMessages, etc…)
Also it does not break .NET native localization, so you still can add App_GlobalResources and App_LocalResources folder and add resources files and use them as discussed here.
Thanks for this post
Hi Mina,
This article is very useful but I’m missing something :
How do I get resources on pages ?
For resources in App_GlobalResources, I simply write :
Thanks
Hello Kewa, to get the resource in your page you just need to:
- reference the culture project in your webapplication/website project.
- retrieve the string by using the key as following:
Example:
Sorry but I can’t see your example.
Apparently the same thing happened to mine…
Maybe a bug of WordPress.
Could you resend it ?
Oh yeah, I can see that. here you are the steps to get the resource in your page again:
- reference the culture project in your webapplication/website project.
- retrieve the string by using the key as following:
<%= [Custom tool namespace].[resource file name].[resource string key] %>
Example:
<%= MyResources.Global.stringKey %>
Ok I will test this way instead of :
<%$ Resources:BMW.GestionSinistres, damage_declaration %>
@WordPress : please notice that ASPX isn’t html ^^