20 tips for ASP. net mvc 3 Development (4) [20 recipes for programming MVC 3]: multi-language support

Source: Internet
Author: User
Tags actionlink


There are millions of people from hundreds of countries on the Internet, and there are hundreds of different languages. Even the United Kingdom, the United States, Canada, and the United Kingdom have different dialects. Do not restrict your website browsing because it only provides one language.


Create a resource file, add static text of the key/value type, and implement currentuiculture to provide the ability to change the current real language.


Resource files are XML files that can be stored in multiple languages for websites. When you create a resource file, it contains the current default language. After you create a key/value pair text in a resource, you can use it everywhere in the controller, model, and view. Example 1-3 resource file example.

Legend1-3. Resource file example


Right-click ApplicationProgram, Select "add"-> "create folder", and name the new file "resources ". Right-click the new folder and choose add> new item ". Enter "resource" in the back-side search and select "resource file ".

As shown in, we create entries for all attributes of the "book" model class in the resource file. Next we need to modify the model class and use displayattribute to reference these values:

 Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. Web;
Using System. Data. entity;
Using System. componentmodel. dataannotations;
Using Mvcapplication4.validations;

Namespace Mvcapplication4.models

Public Class Book
Public Int Id { Get ; Set ;}

[Display (name = " Titledisplay " ,
Resourcetype = Typeof (Resources. resource1)]
Public String Title { Get ;Set ;}

[Display (name = " Isbndisplay " ,
Resourcetype = Typeof (Resources. resource1)]
Public String ISBN { Get ; Set ;}

[Display (name =" Summarydisplay " ,
Resourcetype = Typeof (Resources. resource1)]
Public String Summary { Get ; Set ;}

[Display (name = " Authordisplay " ,
Resourcetype = Typeof (Resources. resource1)]
Public String Author { Get ; Set ;}

[Display (name = " Thumbnaildisplay " ,
Resourcetype = Typeof (Resources. resource1)]
Public String Thumbnail { Get ; Set ;}

[Display (name = " Pricedisplay " ,
Resourcetype = Typeof (Resources. resource1)]
[Range ( 1 , 100 )]
Public Double Price {Get ; Set ;}

[Display (name = " Publisheddisplay " ,
Resourcetype = Typeof (Resources. resource1)]
[Datatype (datatype. Date)]
Public Datetime published { Get ; Set ;}


Public Class Bookdbcontext: dbcontext
Public Dbset <book> books { Get ; Set ;}



In the preceding example, displayattribute uses the key name segment to retrieve and reference the corresponding resource value in the resource file. Such a reference can be used on each view and controller.


In the following example, we will change the actual text of the book index view and move the static text to the resource file. For example, create a key/value table in Table 1-1:

Key name












Table1-1 update resource files


So far, only one resource file has been created, and all the key names must be unique throughout the project. As you can see, the five key-value pairs created in the table can be linked to all views.

After updating the resource file, open bookscontroller and use the followingCodeReplace index:

// Get:/books/
Public Viewresult index ()

# Region Viewbag Resources

Viewbag. Title =
Resources. resource1.bookindextitle;

Viewbag. CreateLink =
Resources. resource1.createlink;

Viewbag. titledisplay =
Resources. resource1.titledisplay;

Viewbag. isbndisplay =
Resources. resource1.isbndisplay;

Viewbag. summarydisplay =
Resources. resource1.summarydisplay;

Viewbag. authordisplay =
Resources. resource1.authordisplay;

Viewbag. thumbnaildisplay =
Resources. resource1.thumbnaildisplay;

Viewbag. pricedisplay =
Resources. resource1.pricedisplay;

Viewbag. publisheddisplay =
Resources. resource1.publisheddisplay;

Viewbag. editlink =
Resources. resource1.editlink;

Viewbag. detailslink =
Resources. resource1.detailslink;

Viewbag. deletelink =
Resources. resource1.deletelink;

# Endregion

Return View (db. Books. tolist ());



Finally, the index directory view of a book must change all the text to reference the corresponding attribute of viewbag:

@ Model ienumerable <  Mvcapplication6  . Models. Book  > 

< H2 > @ Viewbag. Title </ H2 >
< P >
@ Html. actionlink (string) viewbag. CreateLink, "CREATE ")
</ P >

< Table >
< Tr >
< Th >
@ Viewbag. titledisplay
</ Th >

< Th >
@ Viewbag. isbndisplay
</ Th >

< Th >
@ Viewbag. summarydisplay
</ Th >

< Th >
@ Viewbag. authordisplay
</ Th >

< Th >
@ Viewbag. thumbnaildisplay
</ Th >

< Th >
@ Viewbag. pricedisplay
</ Th >

< Th >
@ Viewbag. publisheddisplay
</ Th >
< Th > </ Th >
</ Tr >

@ Foreach (VAR item in Model)

< Tr >
< TD >
@ Html. displayfor (modelitem => item. Title)
</ TD >

< TD >
@ Html. displayfor (modelitem => item. ISBN)
</ TD >

< TD >
@ Html. displayfor (modelitem => item. Summary)
</ TD >

< TD >
@ Html. displayfor (modelitem => item. Author)
</ TD >

< TD >
@ Html. displayfor (modelitem => item. thumbnail)
</ TD >

< TD >
@ Html. displayfor (modelitem => item. Price)
</ TD >

< TD >
@ Html. displayfor (modelitem => item. published)
</ TD >
< TD >
@ Html. actionlink (string) viewbag. editlink,
"Edit", new {id = item. ID}) |

@ Html. actionlink (string) viewbag. detailslink,
"Details", new {id = item. ID}) |

@ Html. actionlink (string) viewbag. deletelink,
"Delete", new {id = item. ID })

</ TD >
</ Tr >

</ Table >


Other views and controllers can be modified in this way. After these modifications are completed, we only need to copy the resource file to another language version.

To avoid additional input, we recommend that you complete the program and add all files to the resource file. Right-click the current resource file and click "copy", right-click the "Resources" folder and click "Paste", and rename the copied resource copy file to "resource1.fr. resx ", of course, you can also create and name other copies in the language you want. Then translate the part of the file into the desired language text.

To change the language based on the request, you must change the currentuiculture of each request in the appliation_acquirerequeststate () method of the global. asax. CS file:

        Protected   Void Application_acquirerequeststate (
Object Sender, eventargs E)

If (Httpcontext. Current. session! = Null )

Cultureinfo CI =
(Cultureinfo) This . Session [ " Currentlanguage " ];

If (CI = Null )
Ci = New Cultureinfo ( " En " );
This . Session [ " Currentlanguage " ] = CI;

Thread. currentthread. currentuiculture = CI;

Thread. currentthread. currentculture =
Cultureinfo. createspecificculture (CI. Name );

In the preceding code example, a valid cultureinfo value is assigned to the session variable currentlanguage after detection. If a valid cultureinfo is detected, the system assigns the English language to currentlanguage by default. Next, we will create an action in the home controller to provide users with the language selection function:

PublicActionresult changelanguage (StringLanguage)
Session ["Currentlanguage"] =
NewCultureinfo (language );

ReturnRedirect ("Index");

Changelanguage accepts the parameter for setting the new language name. This parameter variable updates the painting variable in global. asax. CS, and switches to the selected language interface. Add the following link to the global shared master page _ layout. cshtml:

[@ Html. actionlink ( "  English  " , " Changelanguage  " , "  Home  " ,
New {Language = " En " }, Null )]

[@ Html. actionlink ( " Français " , " Changelanguage " , " Home " ,
New {Language = " FR " }, Null )]

We place the link next to the "login" link. As the website develops, we create a new resource file and add a new link, in this way, you can select a new language, which is very easy to add.

We have discussed many different English dialects in Canada, the United States, and the United Kingdom. If you want to add language information for different countries, you can add the language code behind the country code, and connected by the "-" character. For example, "En-GB" indicates UK English. After adding it, you must update the link, language name, And currentuiculture settings.


currentuiculture Source Book Address Source Code

Related Article

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.