淘先锋技术网

首页 1 2 3 4 5 6 7

可以动态切换多个版本的语言,使用资源文件实现

1、新建LanguageHelper.cs 类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Globalization;
using System.Web.SessionState;
using System.Resources;
using System.Collections;
using System.Data;
using Maticsoft.BLL.SysManage;
using Maticsoft.Model.SysManage;

namespace Maticsoft.Web.Components
{
    public class LanguageHelper
    {
        private const string SessionKey = "SessionKey_Language";
        private static HttpSessionState Session { get { return HttpContext.Current.Session; } }
        private static bool SessionExist { get { return Session != null; } }
        private static string SessionLanguage
        {
            get { return (SessionExist && Session[SessionKey] != null) ? (string)Session[SessionKey] : null; }
            set { if (SessionExist) { Session[SessionKey] = value; } }
        }
        private static CultureInfo CultureInfo 
        { 
            get { return Thread.CurrentThread.CurrentUICulture; }
            set { Thread.CurrentThread.CurrentUICulture = value; }
        }
        public static string CultureLanguage
        {
            get { return CultureInfo.Name.Split('-').First(); }
            private set { CultureInfo = new CultureInfo(value); }
        }
        public static void Initialize()
        {
            string sessionLanguage = SessionLanguage;
            if (sessionLanguage != null && sessionLanguage != CultureLanguage)
                CultureLanguage = sessionLanguage;
        }
        public static void ChangeLanguage(string language, bool isRedirect = true)
        {
            SessionLanguage = language;
            if (isRedirect)
                HttpContext.Current.Response.Redirect(HttpContext.Current.Request.Url.ToString());
        }
        public static void Initialize(HttpRequest request)
        {
            if (SessionLanguage == null)
                SessionLanguage = request.UserLanguages[0];
            Initialize();
        }
        public static void Initialize(string language)
        {
            SessionLanguage = language;
            Initialize();
        }
        public static Dictionary<string, string> GetLanguageList(bool isFromDB = true)
        {
            Dictionary<string, string> dic = new Dictionary<string,string>();
            if (isFromDB)
            {
                List<Language> list = new LanguageBLL().GetAllLanguage();
                foreach (Language temp in list)
                {
                    dic.Add(temp.LanguageCode, temp.GetContentValue(CultureLanguage));
                }
            }
            else
            {
                ResourceSet rs = Resources.Language.ResourceManager.GetResourceSet(CultureInfo, true, true);
                IDictionaryEnumerator en = rs.GetEnumerator();
                while (en.MoveNext())
                {
                    dic.Add((string)en.Key, (string)en.Value);
                }
            }
            return dic;
        }

        public static DataSet FormatSysTree(DataSet data, string columnName = "TreeText")
        {
            if (data != null && data.Tables.Count > 0)
            {
                DataTable tab = data.Tables[0];
                if (tab.Rows.Count > 0)
                {
                    Maticsoft.BLL.SysManage.SysTree bll = new Maticsoft.BLL.SysManage.SysTree();
                    foreach (DataRow row in tab.Rows)
                    {
                        Model.SysManage.SysNode model = bll.DataRowToModel(row);
                        row[columnName] = model.GetContentValue(CultureLanguage);
                    }
                }
            }
            return data;
        }

        public static string FormatPaymentType(string name, string defaultText = null)
        {
            return GetString(Resources.PaymentType.ResourceManager, name, defaultText);
        }

        public static string FormatOrderStatus(Maticsoft.Model.Shop.Order.EnumHelper.OrderStatus orderStatus, string defaultText = null)
        {
            return GetString(Resources.OrderStatus.ResourceManager, orderStatus.ToString(), defaultText);
        }

        public static string FormatShippingStatus(Maticsoft.Model.Shop.Order.EnumHelper.ShippingStatus shippingStatus, string defaultText = null)
        {
            return GetString(Resources.ShippingStatus.ResourceManager, shippingStatus.ToString(), defaultText);
        }

        public static string FormatOrderMainStatus(Maticsoft.Model.Shop.Order.EnumHelper.OrderMainStatus orderMainStatus, string defaultText = null)
        {
            return GetString(Resources.OrderMainStatus.ResourceManager, orderMainStatus.ToString(), defaultText);
        }
        public static string FormatMarketingCenter(Maticsoft.Model.CRM.Enum.ActivitysType typeName, string defaultText = null)
        {
            return GetString(Resources.OrderStatus.ResourceManager, typeName.ToString(), defaultText);
        }

        

        public static string FormatEnumItemName(Enum e, string defaultText = null)
        {
            Type type = e.GetType();
            ResourceManager resourceManager = GetResourceManagerByName(type.Name);
            if (resourceManager == null)
                return defaultText;
            return GetString(resourceManager, Enum.GetName(type, e), defaultText);
        }

        public static string FormatEnumItemDescription(Enum e, string defaultText = null)
        {
            Type type = e.GetType();
            ResourceManager resourceManager = GetResourceManagerByName(type.Name);
            if (resourceManager == null)
                return defaultText;
            return GetString(resourceManager, string.Format("{0}_Description", Enum.GetName(type, e)), defaultText);
        }

        public static ResourceManager GetResourceManagerByName(string name)
        {
            try { return new ResourceManager(string.Format("Resources.{0}", name), System.Reflection.Assembly.Load("App_GlobalResources")); }
            catch { return null; }
        }

        public static string GetString(ResourceManager resourceManager, string name, string defaultText = null)
        {
            if (!string.IsNullOrEmpty(name))
            {
                string text = resourceManager.GetString(name);
                if (!string.IsNullOrEmpty(text))
                    return text;
            }
            return defaultText == null ? name : defaultText;
        }
    }
}
View Code

2、在Global中初始化语言

 protected virtual void Application_AcquireRequestState(object sender, EventArgs e)
        {
            try
            {
                //LanguageHelper.Initialize(Request);//设置系统显示语言
                LanguageHelper.Initialize("en");//设置系统显示语言
            }
            catch (Exception) { }
        }

上面代码,使用Request可以根据浏览器系统语言,设置初始化语言,下面字符串可以设定指定的默认语言。

 

MultiLanguageModel.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Maticsoft.Model.Language
{
    public class MultiLanguageModel
    {
        private readonly Dictionary<string, string> _resources = new Dictionary<string, string>();
        public string DefaultContentValue { set; get; }
        public void AddResources(IResources resources)
        {
            if (string.IsNullOrEmpty(resources.LanguageCode))
            {
                DefaultContentValue = resources.ContentValue;
            }
            else
            {
                if (_resources.ContainsKey(resources.LanguageCode))
                    _resources[resources.LanguageCode] = resources.ContentValue;
                else
                    _resources.Add(resources.LanguageCode, resources.ContentValue);
            }
        }
        public void AddResources(IEnumerable<IResources> resources)
        {
            foreach (IResources ir in resources)
            {
                AddResources(ir);
            }
        }
        public IEnumerable<IResources> Resources
        {
            set
            {
                _resources.Clear();
                AddResources(value);
            }
        }
        public string GetContentValue(string languageCode)
        {
            return _resources.ContainsKey(languageCode) ? _resources[languageCode] : DefaultContentValue;
        }
    }

    public interface IResources
    {
        string LanguageCode { set; get; }
        string ContentValue { set; get; }
    }
}
View Code

 

页面初始化语言下拉框:

 private void InitLanguageList()
        {
            Dictionary<string, string> language = LanguageHelper.GetLanguageList(false);
            if (language != null && language.Count > 0)
            {
                string selected = language.ContainsKey(LanguageHelper.CultureLanguage) ? LanguageHelper.CultureLanguage : "zh";
                foreach (KeyValuePair<string, string> kvp in language)
                {
                    this.languageList.Items.Add(new System.Web.UI.WebControls.ListItem(kvp.Value, kvp.Key)
                    {
                        Selected = selected == kvp.Key
                    });
                }
                
                if (LanguageHelper.CultureLanguage != this.languageList.SelectedValue)
                    LanguageHelper.ChangeLanguage(this.languageList.SelectedValue, false);
            }
            else
            {
                this.languageList.Visible = false;
            }
        }
View Code
protected void languageList_SelectedIndexChanged(object sender, EventArgs e)
        {
            LanguageHelper.ChangeLanguage(this.languageList.SelectedValue);
        }
<asp:DropDownList ID="languageList" runat="server" AutoPostBack="True" OnSelectedIndexChanged="languageList_SelectedIndexChanged></asp:DropDownList>

 

页面调用:

 <div class="vinfo">
                        <%=Resources.Admin.Text_SystemDescription %>
                    </div>


 <asp:TextBox ID="txtBusinessCode" Text="" runat="server" TabIndex="1" CssClass="ipt"
                                        placeholder="<%$ Resources:Admin,Lable_BusinessCode %>">
                                    </asp:TextBox>

 

转载于:https://www.cnblogs.com/SmilePastaLi/p/7390587.html