這是我第一次寫的博客,有錯誤麻煩指出。謝謝。
要考慮的問題:
1、資源文件的存放位置:App_GlobalResources?DLL文件還是數據庫?
2、要本地化的範圍:整站?還是一個網頁?還是某個網頁的部分控件?
3、本地化的對象有哪些?(基本上是控件了)datagrid控件、literal控件、button控件、check控件等等……
基本上涉及的就這些問題。
步驟一:
1、因爲快捷的原因,我選擇用App_GlobalResources來存放資源文件。如果要把資源文件存放在dll文件和數據庫中,可以參考MSDN:擴展 ASP.NET 2.0 資源提供程序模型。
2、本地化確定爲整站,要保持整站本地化狀態,可以用會話狀態來存儲。
3、把本地化對象放入容器中,如panel控件。約定控件ID和資源ID相同。建立一個類來對某一個容器的控件進行本地化:
public class FormGlobaling
{
/// <summary>
/// 對頁面某一容器中的控件執行本地化操作
/// </summary>
/// <param name="container">容器控件:比如:panel等控件</param>
/// <param name="resourcefilename">本地化資源文件名字</param>
public static void GlobalingControls(Control container, string resourcefilename)
{
try
{
foreach (Control ct in container.Controls)
{
if (ct is ListControl)
{
ListControl drlist = (ListControl)ct;
for (int i = 0; i < drlist.Items.Count; i++)
{
drlist.Items[i].Text = HttpContext.GetGlobalResourceObject(resourcefilename, drlist.ID.ToString() + i.ToString()).ToString();
}
}
else if (ct is CheckBox)
{
CheckBox cb = (CheckBox)ct;
cb.Text = HttpContext.GetGlobalResourceObject(resourcefilename, cb.ID.ToString()).ToString();
}
else if (ct is Literal)
{
Literal lt = (Literal)ct;
lt.Text = HttpContext.GetGlobalResourceObject(resourcefilename, lt.ID.ToString()).ToString();
}
else if (ct is LinkButton)
{
LinkButton lk = (LinkButton)ct;
lk.Text = HttpContext.GetGlobalResourceObject(resourcefilename, lk.ID.ToString()).ToString();
}
else if (ct is Label)
{
if (ct is RequiredFieldValidator)
{
RequiredFieldValidator rb = (RequiredFieldValidator)ct;
rb.ErrorMessage = HttpContext.GetGlobalResourceObject(resourcefilename, rb.ID.ToString()).ToString();
}
else if (ct is CompareValidator)
{
CompareValidator cv = (CompareValidator)ct;
cv.ErrorMessage = HttpContext.GetGlobalResourceObject(resourcefilename, cv.ID.ToString()).ToString();
}
}
else if (ct is Button)
{
Button bt = (Button)ct;
bt.Text = HttpContext.GetGlobalResourceObject(resourcefilename, bt.ID.ToString()).ToString();
}
//等等,其他控件形式等待加入,注意:請排除Textbox控件和其他與數據庫交互的控件。
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
4、通過使用“GlobalingControls(Control container, string resourcefilename)”來實施本地化,其中container爲控件容器,resourcefilename爲資源文件的名稱。