Implement multi-language environment in MVC

Source: Internet
Author: User

1. Global. CS

Code

1 /// <summary>
2 // start to switch the language for each request
3 /// </Summary>
4 /// <Param name = "sender"> </param>
5 /// <Param name = "E"> </param>
6 protected void application_beginrequest (Object sender, eventargs E)
7 {
8 string culture = "En-us ";
9 httpcookie cookie = request. Cookies ["Lang"];
10 if (cookie = NULL)
11 {
12 if (request. userages! = NULL) & (request. userages. length> 0 ))
13 {
14 culture = request. userages [0];
15}
16}
17 else
18 {
19 culture = cookie. value;
20}
21 system. Globalization. cultureinfo = NULL;
22 try
23 {
24 cultureinfo = new system. Globalization. cultureinfo (Culture );
25}
26 catch
27 {
28 cultureinfo = new system. Globalization. cultureinfo ("En-us ");
29}
30 system. Threading. thread. currentthread. currentculture = cultureinfo;
31 system. Threading. thread. currentthread. currentuiculture = cultureinfo;
32}

 

 

2. Language Switching

Code

1 /// <summary>
2 // select a language
3 /// </Summary>
4 /// <Param name = "Lang"> </param>
5 /// <returns> </returns>
6 Public actionresult selectlanguage (string Lang)
7 {
8 httpcookie cookie = new httpcookie ("Lang ");
9 cookie. value = string. isnullorempty (Lang )? "ZH-CN": Lang. Trim ();
10 cookie. expires. adddays (1 );
11 response. Cookies. Remove ("Lang ");
12 response. Cookies. Add (cookie );
13
14 string redirecturl = "/";
15 if (request. urlreferrer! = NULL)
16 {
17 redirecturl = request. urlreferrer. pathandquery;
18}
19
20 return redirect (redirecturl );
21}

 

 

3. Add app_globalresources

Resource. resx
Resource. zh-CN.resx

 

4. Use in code
CS: resources. Resource. Name

View: <% = resources. Resource. name %>

 

5. query the language selected by the current user in JS

 

1 function getclientlang (){
2 var L = getcookie ("Lang") | navigator. browserlanguage | navigator. Language | "ZH-CN ";
3 return L. tolowercase ();
4}
5

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.