Example of multi-language website construction in mvc4

Source: Internet
Author: User
Tags actionlink

Environment: vs2012 Asp.net mvc4.

Implementation Method: resource file, based on the Lang parameter in the routing rule to determine which language to load

I found the relevant information on the Internet and made an exercise by myself. The steps such as creating a project are no longer required. Please note that it is easy to use it next time.

1: Add a resource file. Remember to set the access mode of the resource file to public. Otherwise, the default access mode is internal, and access from outside will fail:

 

2: Add a routing rule. Remember to add it before the default routing rule. Otherwise, the new rule is useless. For details, refer to this article.

1 routes. add (new route (2 "{Lang}/{controller}/{action}/{ID}", 3 new routevaluedictionary (New {4 lang = "En-us ", // The default value is e File 5 controller = "Account", 6 action = "Logon", 7 id = urlparameter. optional 8}), 9 new multilangroutehandler () // This class is mainly used to get the current Lang value 10 through gethttphandler ));

 

 1 public class MultiLangRouteHandler : MvcRouteHandler { 2         protected override IHttpHandler GetHttpHandler(RequestContext requestContext) { 3             string lang = requestContext.RouteData.Values["lang"].ToString(); 4  5             //Thread.CurrentThread.CurrentCulture = new CultureInfo(lang); 6             Thread.CurrentThread.CurrentUICulture = new CultureInfo(lang); 7  8             //return new MvcHandler(requestContext); 9             return base.GetHttpHandler(requestContext);10         }11     }

For details about currentuiculture in the code, refer to the previous article.

3: entry for switching between Chinese and English.

1 <div> 2 @ {3 string controller = viewcontext. controller. valueprovider. getvalue ("controller "). rawvalue. tostring (); 4 string action = viewcontext. controller. valueprovider. getvalue ("action "). rawvalue. tostring (); 5 // string lang = viewcontext. controller. valueprovider. getvalue ("Lang "). rawvalue. tostring (); 6} 7 @ HTML. actionlink ("Chinese", action, new {controller = controller, lang = "ZH-CN"}, new {@ class = "BTN-a"}) 8 @ HTML. actionlink ("English", action, new {controller = controller, lang = "En-us"}, new {@ class = "BTN-a"}) 9 </div>

4: multiple languages of common text on the Interface

In fact, I wrote the test program according to the article above, but the dead resource file is not switched based on Chinese and English. I don't know if there is a problem or not ~, Later, my friend (heartless water) in the MVC group introduced another article. I wrote it with reference. Here I say ths...

Public static class langhelper {// multilingual public static string getlangbykey (this htmlhelper, string key) {type resourcetype = (thread. currentthread. currentuiculture. name = "En-us ")? Typeof (resources. en_us): typeof (resources. zh_cn); propertyinfo P = resourcetype. getproperty (key); If (P! = NULL) return p. getvalue (null, null ). tostring (); else return "undefined";} // JS definition multilingual pop-up box public static string langoutjsvar (this htmlhelper, string key) {type resourcetype = (thread. currentthread. currentuiculture. name = "En-us ")? Typeof (resources. en_us): typeof (resources. zh_cn); propertyinfo P = resourcetype. getproperty (key); If (P! = NULL) return string. format ("Var {0} = '{1}'", key, P. getvalue (null, null ). tostring (); else return string. format ("Var {0} = '{1}'", key, "undefined ");}}

The view page calls the function directly. For example: <H2> @ html. getlangbykey ("logondisplay") </H2>

5: Multilingual displayname

Redefine the localdisplayname attribute, which inherits from displaynameattribute

public class LocalDisplayName : DisplayNameAttribute {        private string _defaultName = "";        public Type ResourceType {            get { return (Thread.CurrentThread.CurrentUICulture.Name == "en-US") ? typeof(Resources.en_US) : typeof(Resources.zh_CN); }        }        public string ResourceName {            get;            set;        }        public LocalDisplayName(string defaultName) {            _defaultName = defaultName;        }        public override string DisplayName {            get {                PropertyInfo p = ResourceType.GetProperty(ResourceName);                if (p != null)                    return p.GetValue(null, null).ToString();                else                    return _defaultName;            }        }    }

Change the display attribute to localdisplayname in the model class.

public class Account {        [Required]        [LocalDisplayName("user name", ResourceName = "UserDisplay")]        public string UserName { get; set; }        [Required]        [LocalDisplayName("password", ResourceName = "PwdDisplay")]        public string Pwd { get; set; }        [Required]        [Compare("Pwd",ErrorMessageResourceName="ConfirmPwdErrorDisplay")]        [LocalDisplayName("confirm password", ResourceName = "ConfirmPwdDisplay")]        public string ConfirmPwd { get; set; }                [Required]        [LocalDisplayName("remember", ResourceName = "RemDisplay")]        public bool Rememberme { get; set; }    }

Call method: <div> @ html. labelfor (M => M. username) </div>

 

Effect:

 

This is basically achieved. There is an errormessage which is not complete yet. If you have time, write it again. If anything is wrong, please correct me. Thank you!

Reference:

Http://www.cnblogs.com/codehunter008/archive/2008/09/01/1281565.html

Http://www.cnblogs.com/lionking/articles/1894277.html

How can I implement multiple languages if I want to write Database Text? For more information, see.

Download link: Click to download

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.