Thursday, July 24, 2014

Step by step how to create resource files and localized views in ASP.NET MVC

In this tutorial we'll learn how to create resource files and localized views in ASP.NET MVC.
We'll generate .resx resource files , which consist of XML "data" and "value" entries, specifying string keys and its corresponding messages. Visual Studio comes with a designer to edit the entries, but every text editor  as Notepad++ or Word can take care of the data in a resources file.
We will design a sample Form in both English and Spanish, as follows:

To create a resources file, you select the proper folder and add a .resx file:

Then you open the file and using the designer you add the key/value pairs as follows:

In MVC, the resource files will be translated into classes and embedded in the application assembly. In order to achieve that, we must be careful with three things:
1) we must set the tool which creates the classes, to generate PUBLIC classes, setting in the "Properties" of the resx files , the "Custom Tool" to "PublicResXFileCodeGenerator":

2) we must be careful to create some folder structure of resources reflecting our application structure, and that will appear as the Namespace of the Resource Classes. Meaning that the following folder structure:

...will be reflected in the following Namespace hierarchy:

3) According to the later point, we can place the resx files which are global to the whole application, in an upper folder, and those which are specific to the Views, in some more specific folder:

After you built all resx files, you compile the application , and you could see the .cs files corresponding to each resources file in its proper class:

Then you just insert into the Views the reference to the Resources Classes with the proper localization :

So the same Form can be shown with an English or an Spanish interface , as you wish:

And if you change only the resources class, you get all language changes automatically:

That's all!!  In this tutorial we've learned MVC localization and how to create resource files and localized views in ASP.NET MVC.

Happy programming.....
        By Carmel Schvartzman
כתב: כרמל שוורצמן