[Turn].Net to achieve localization simple tutorial

This article is reproduced from: https://www.cnblogs.com/csdbfans/archive/2011/10/17/2214048.html

 

The realization of multi-language version support is the so-called internationalization, which is also called localization.

What will be introduced here today is the introduction of localization in .Net. There are many articles on the Internet on how to achieve localization, but most of them are not suitable for beginners to learn, because beginners need more detailed introductions and charts as instructions.

So with the idea of ​​learning from each other, I also write about my recent learning experience.

First, some knowledge is required here. Of course, you can choose from the text what you need to read.

What we want to explain here is the global resource file, which is stored in the App_GlobalResources folder . It is very simple to create this folder in the Web Form . Right-click the project (WebSite or Application) in the " Resource Manager of the Solution " and select Add->Add ASP.NET Folder->App_GlobalResources (as shown in the following figure). There can only be one such folder in the application, and it is in the root directory of the application. Of course, the resource files in it are not unique.

 

unnamed

 

There is another kind of local resource file, which is similar to the global resource file. The difference is that the name of the folder stored is different. The local resource folder is App_LocalResources . Within the application, there is no limit to the number of such folders, nor is it limited to their location.

The first point: realize the localization of Asp.net server-side controls .

It is very simple to realize the localization of Asp.net server-side controls. Once you want to add localization information to the server-side controls, you can follow the steps below to implement your localization operations. Enter the design window, and then click on one of the server -side controls , and then select " Tools -> Generate Local Resource " on the menu (as shown below). Then VS2010 will create the resource file for this page for you. Then in the application, you will find an additional folder App_LocalResources , and there is an additional resource file named after the editing page just now. The edited page is the Login.aspx page. At this time, you will see in Login.aspx that VS2010 has generated a new directory App_LocalResources , and there is an additional file Login.aspx.resx. Note that the naming of the localization files here is fixed and cannot be changed. One localization file corresponds to one page file.

 

1

2

Double-click the resource file Login.aspx.resx , and enter the Value you need in the Value box. The Name value in the resource file is the property in the Login.aspx server control. It needs to be mentioned here that resource files are not limited to text formats, but also include resource files in many formats. In the figure below, there is a " Strings" drop-down box (downward triangle) under Login.aspx.resx , click to select the resource file to be added, and click the "Add Resource" drop-down box to select add.

3

After adding the resource file, the localization of the server-side control is completed. At this time, after you run Ctrl+F5, you can see that the content of your login page (Login.aspx) is the content of the resource file you filled in. The content of the resource file here (the Value value corresponding to Name was just written in the picture above) I will not post the Login.aspx.resx picture, I will post the result. Login.aspx.resx is a file automatically generated by the tool, so you can delete or modify the columns you do not need.

4

In fact, there is another picture to explain here. I don't know if you have seen an additional attribute in the code of each server-side control. Similar to meta:resourcekey=" RegisterHyperLinkResource1".

5

What needs to be explained here is that it only works on server-side controls, not the text of server-side controls, if you also want to do it in the way of resource files. The following will use another control to do (<asp:Localize>)。回过头来说,我们是实现对多语言的支持,那么资源文件当然是需要多个的,比如再创建一个叫Login.aspx.en.resx的资源文件在App_LocalResources里面。

6

改变浏览器阅读网站首选项的语言,再刷新浏览器里面Login.aspx页面,你就会发现里面使用的语言变成是英语,而不是刚才的中文。改变浏览器阅读网站语言的设置如下:以IE做说明,IE菜单:工具->Internet选项->语言->添加->选择英语。这里之后需要注意的是:英文需要排在第一位,不然不会起作用

未命名7

 

上面介绍了怎么实现Asp.Net里面服务端控件的本地化,那普通的文本呢?其实普通的文本也可以支持到。但是感觉普通的文件其实跟用个Label的方式来做有什么不同了?

许就是Label会自动生成更多的Name名(在资源文件里面),省去我们删除的工作吧。所以人家微软给你另一种支持了,如果你觉得可以用,那就用吧。拿上文登录页Login.aspx页面的代码来说吧:

copy code
    <p>Please enter your username and password.           

          <asp:HyperLink ID="RegisterHyperLink" runat="server" EnableViewState="False"
             meta:resourcekey="RegisterHyperLinkResource1"> Register</asp:HyperLink>           

          if you don't have an account.
   </p>
copy code

Here we can use<asp:Localize>服务端控件,这个控件位于工具箱里的标准类别里面。加入了Localize后代码如下所示:

copy code
    <p>
         <asp:Localize ID="Header" runat="server"> Please enter your username and password.</asp:Localize>           

        <asp:HyperLink ID="RegisterHyperLink" runat="server" EnableViewState="False"
              meta:resourcekey="RegisterHyperLinkResource1">Register</asp:HyperLink>           

        <asp:Localize ID="Footer" runat="server"> if you don't have an account.</asp:Localize>
    </p>
 
copy code

In fact, after this step, we need to use a property we mentioned abovemeta:resourcekey="HeaderResource1”,然后在资源文件里面写需要显示的内容。
这里面如果你不
知道资件里面的Name值是什么的话,其实也可以跟开始那样,在设计视窗里面点击里面的服务端控件,然后“Tools->Generate Local Resource”。这后之后它就会变成如下代码:

copy code
<p> <asp:Localize ID="Head" runat="server" meta:resourcekey="HeadResource1"
              Text="Please enter your username and password."></asp:Localize>

          <asp:HyperLink ID="RegisterHyperLink" runat="server" EnableViewState="False"
              meta:resourcekey="RegisterHyperLinkResource1"Text="Register">
         </asp:HyperLink>           

         <asp:Localize ID="Footer" runat="server" meta:resourcekey="FooterResource1"  

              Text=" if you don't have an account."></asp:Localize>
   </p>
copy code

Then in the resource file, you can also see the corresponding changes, but it only changes a default resource file, and other resource files in different languages ​​will not change synchronously
There is one more place I want to explain in the picture below, and that is the Access Modifier drop-down box at the bottom, which contains three access rhetoric characters. Public is for public access, Internal is for access in the program, and No code generation should be this kind of access that does not require code.

8
 

The above mentioned are only the contents of the local resource files. Now we will introduce how the resource files in the global resource folder are used. What is introduced here is to use code to achieve localization. When it comes to global resource files, that is the resource files in the App_GlobalResources file. I think everyone knows the method of adding this folder. It was introduced at the beginning of this article, which is the same as the method of the local resource folder. Then we will create our global resource file GlobalResource.resx.

9
10

It is necessary to look at the post file of GlobalResource.resx----GlobalResource.Designer.cs.

11
12

After adding Name as Test and Value as test content in the global resource file, you will find that the following content has been added to its postcode (GlobalResource.Designer.cs) file:

copy code
internal static string Test {
             get {

                 return ResourceManager.GetString("Test", resourceCulture);

             }
       }
copy code

This code should not be difficult to understand, it uses the Test property to take the text value. It should be noted here that it is an internal access rhetoric , and a static property. Therefore, after you add the name space of this class to the code, you can obtain the content of the text in the resource file through the attribute method of the class. Of course, other resource types are obtained in the same way, except that the return type of the attribute is different. .

(1) Get it directly in the cs code: string content = Resources.GlobalResource.Test
(2) Resource expression:
<asp:Localize ID="Head" runat="server"  Text="<%$ Resources:GlobalResource, Test %>"></asp:Localize>
Here Resources is the name space , GlobalResource is the class name , Test is the attribute in the class, and the value of the resource file is obtained through them.
(3) Use the GetGlobalResourceObject method:
string content = GetGlobalResourceObject("GlobalResource", "Test").ToString();
Here the GetGlobalResourceObject method returns an Object .
For comparison, the local approach:
(1)Resource表达式:<asp:Localize ID="Head" runat="server" 
Text=" <%$ Resources:LoginButtonResource1.Text %> "></asp:Localize>
This is the binding method of the local resource file. In the local resource file, there is no corresponding post file, that is, there is no .cs file, and the value is directly obtained in a fixed way. Resources is
The default name indicates the space name. Unlike the global one, which can be changed ( at least I didn't find it ), the name after the colon is the Name value in the local resource file.
(2) meta:resourceKey is the implementation of server-side control localization .
(3) GetLocalResourceObject method, similar to GetGlobalResourceObject.
Finally, as a closing introduction. Let's talk about the way to achieve dynamic localization .
Here we still take the login page (Login.aspx) as an example to illustrate, adding a language selection drop-down box in the page, allowing users to select the desired language for localization.
Login.aspx.cs code is as follows:
copy code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Globalization;

namespace ResourceWebForm.Account {

     public partial class Login : System.Web.UI.Page     {

          protected void Page_Load(object sender, EventArgs e)         {

          }

          // enumerate language types
          enum Language
          {
              English,
             Chinese
         }

         protected override void InitializeCulture()  {

            //Get the value in the select drop-down box
          string language = Request.Form["ddlLanguageName"];
          string languageId = "";

            if (!string.IsNullOrEmpty(language)) {
               try {
                 // convert string to enum type
                 Language enumLanguage=(Language)System.Enum.Parse(typeo(Language),language);

                   switch(enumLanguage)  {
                       case Language.Chinese:
                           languageId = "zh-CN";
                           break;
                       default:
                           languageId = "en-US";
                           break;
                   }

               }catch(Exception ex){

                   languageId = "en-US";

               }

               Thread.CurrentThread.CurrentCulture=CultureInfo.CreateSpecificCulture(languageId);
             Thread.CurrentThread.CurrentUICulture = new CultureInfo(languageId);

            }
              base.InitializeCulture();
         }
     }
}
copy code

Compared with the previous content in the Login.aspx page, only a drop-down box and a button are added to submit the language change (the code at the bottom of the figure below). Here, the localization effect is achieved by overriding the method InitializeCulture() of the parent class. This method is used to initialize the culture and UICulture information of the page. In ASP.NET Web pages, you can set the values ​​of these two cultural characteristics, the  Culture  and UICulture  properties. The Culture  value determines the outcome of functions related to cultural properties (eg, date, number, and currency formats, etc.).
The UICulture  value is determined as the resource loaded by the web page. If you want to know more, you can refer to this link Page.InitializeCulture method. Regarding the languageId of the above code, if you don't know the abbreviation of the language, you can use the above method, in the browser: IE menu: Tools->Internet Options->Language->Add , so you know each language What is the abbreviation for .

18
<p>
         <select id="ddlLanguage" name="ddlLanguageName">
             <option value="English" selected="selected">English</option>
             <option value="Chinese">Chinese</option>
         </select>           <asp:Button ID="ChangeBtn" runat="server" Text="Change Language" />
   </p>

The main change here is the content of the files in the App_LocalResources local resource folder (Login.aspx.resx and Login.aspx.zh.resx), the practice of the global resource file is also similar to the practice of the local resource file
12

13
Conclusion: This article has basically briefly introduced the use of Resource resource files. If you think there is any problem, please point it out. After all, I just started learning not long ago. 
Under your teaching, I believe that I can learn more Okay. At least the collision of thinking can make us understand more thoroughly. If you feel that this article is still in the past and want to reprint, please be sure to add this mark .
Finally, I wish you all a happy learning :)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324988362&siteId=291194637