.NET资源文件实现多语言切换
1.創建對應的資源文件
lang.en.resx ?英文
lang.resx ? 中文,默認
lang.zh-tw.resx ?繁體
首先說明,這三個文件前面部分名稱需要一樣,只是 點 后面的語言代號不一樣(en,空,zh-tw)。
語言代號不要亂寫,需要對應系統中對應的語言代號,下面會用到。
創建完成后,只有默認的那個,lang.resx 包含lang.Designer.cs 文件,當你先創建 lang.resx 后,再創建其他兩個,不會再生成Designer.cs 文件了。
當你向資源文件中添加數據的時候,記得,三個文件中的數據的鍵key 要一樣,值不一樣。
例如:
不然切換的時候,出錯。
?
2.如果想要在頁面中使用 ?資源文件,lang.Designer.cs 文件中的internal需要替換為 public,
注意,每次你修改 資源文件,他都會自動變成 internal,需要批量替換成public,要不然沒有智能提示;而且編譯通過,但運行會報錯的。
例:
給他批量替換成public
?
如果你再新增一個Email,剛才替換的internal就又出現了。
替換后,前臺頁面再寫的話,就又提示了,也不報錯。
?
3.代碼設置
切換語言的時候,向這個頁面傳值進來,設置cookie
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls;namespace WebApplication1 {public partial class ChangeLan : System.Web.UI.Page{/// <summary>/// /// </summary>/// <param name="sender"></param>/// <param name="e"></param>protected void Page_Load(object sender, EventArgs e){//切換語言 空:采用默認語言,zh-tw:繁體 en:英文string lan = Request.QueryString["lan"] + "";//寫入cookieHttpCookie hc = new HttpCookie("language");hc.Value = lan;hc.Expires = DateTime.Now.AddDays(1);Response.AppendCookie(hc);//返回到來源頁,所有頁面都繼承 MultiLanguageBase 類,實現多語言 Response.Redirect(Request.UrlReferrer.ToString());}} }?
來源頁面:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title></title></head> <body><form id="form1" runat="server"><div><%=WebApplication1.lang.Name %><br /><%=WebApplication1.lang.Address %></div><a href="ChangeLan.aspx?lan=en">english</a><a href="ChangeLan.aspx">chinese</a><a href="ChangeLan.aspx?lan=zh-tw">TW</a></form> </body> </html> using System.Web.Script.Serialization; using System.Data; using System.Configuration; using System.Globalization; using System.Threading;namespace WebApplication1 {//繼承MultiLanguageBase public partial class WebForm1 : MultiLanguageBase
{
protected void Page_Load(object sender, EventArgs e) { }
}
}
?
基類:
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; using System.Web;namespace WebApplication1 {public class MultiLanguageBase : System.Web.UI.Page{/// <summary>/// 加載之前;所有頁面都繼承這個類/// </summary>/// <param name="e"></param>protected override void OnPreLoad(EventArgs e){base.OnPreLoad(e);string lan = "";if (Request.Cookies["language"] != null){lan = Request.Cookies["language"].Value + "";}var culture = new CultureInfo(lan);Thread.CurrentThread.CurrentUICulture = culture;Thread.CurrentThread.CurrentCulture = culture;}} }?
效果:
?
轉載于:https://www.cnblogs.com/xsj1989/p/4774695.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的.NET资源文件实现多语言切换的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mybatis 批量查询参数语句
- 下一篇: 火箭固体燃料是什么材料