ASP.NET MVC localization best practice?

前端 未结 6 1498
野性不改
野性不改 2020-12-13 10:52

I need help with the best practice to localize asp mvc apps, I saw Oxite having a base method named Localize in the BaseController, but is the Localization a task for the vi

6条回答
  •  攒了一身酷
    2020-12-13 11:16

    Since this a one year question and I don't know the scope of my answer over here. Recently I faced a situation like this , ie I need to implement the localization for different languages in my mvc site.

    I considered using Resource file. its very easy to implement, but the issue is that during the phase of development, we need to specify the localized strings. So if it a multi language support, we need to make the resource file for every language. If client what to change or add a new language, its very difficult and we need to provide a build.

    Second I consider the Satelite Assemblies. Its also similar to Resource, but it gives a freedom to edit the assemblies out side and put it back to bin folder. This also requires a lot of effort to client/developer.

    Third I considered storing in db. This approach is fine and we have some mechanism to read data from the server. This requires one time effort and client doesn't have any dependable .

    I override a custom DisplayNameAttributre and from the constructor I will pass DB and get the data to render

    Based on your requirement it should display the view to you.

    Resource Manager

    /// 
        ///  Extended display attribute which will handles the request
        ///  It will call every time when the property is rendered (return View() - from controller)
        /// 
        public class ResourceManagerAttribute : DisplayNameAttribute
        {
            public ResourceManagerAttribute(string resourceKey, string resourceNameSpace = "")
                : base(GetDisplayName(resourceKey, resourceNameSpace))
            { }
    
            private static string GetDisplayName(string resourceKey, string resourceNameSpace = "")
            {
                // get the browser's prefered language.
    
                string browserLanguage = HttpContext.Current.Request.UserLanguages.First();
    
                // Get the locale data for that property and displays.
                switch (browserLanguage)
                {
                    case "en-US": return "Eng " + resourceKey;
                 // calls db based on resource key
                    case "hi": return "Hin " + resourceKey;
    
                }
                return "-- Not Implemented Now -- ";
            }
    

    ViewModel

    public class HomeViewModel
        {
            //calls the resource
            [ResourceManager("MID")]
            public int MID { get; set; }
            [ResourceManager("Name")]
            public string Name { get; set; }
            [ResourceManager("Addess")]
            public string Addess { get; set; }
        }
    

提交回复
热议问题