在运行时使用资源文件进行本地化

时间:2014-09-22 03:37:52

标签: asp.net webforms localization runtime globalization

我有一个具有本地化的webform。我添加了西班牙语作为webform的第二语言,并且它非常有效。但我发现这个问题,我只能用英语或西班牙语用一种语言启动webform,但我想在运行时更改它。

我想通过在webform中添加以下功能来进一步改进这一点

1)在运行时通过下拉框(英语或西班牙语)选择语言。

2)首先显示默认语言english,如果用户想要更改,则用户应从下拉框中选择

上面提到的2个功能是否可以添加?如果是这样,请说明如何。

这是我的网络表单代码:

                   <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="About_Company.aspx.cs" Inherits="AutoMobileWebsite.AboutUs" UICulture="es-ES"%>

        <!DOCTYPE html>

    <html xmlns="http://www.w3.org/1999/xhtml">
   <head runat="server">
    <title>Company</title>
  </head>
  <body>
  <form id="form1" runat="server">

  <div>
        <asp:Label id="lblAboutCM" runat="server" meta:resourcekey="lblAboutCM"><h1>About Company :</h1></asp:Label> 
</div>

    <div>   
    <asp:Label id="lblContent" runat="server" meta:resourcekey="lblContent"> <h3> The company was established in 2014 by the founder Rex Chris. 
        The intention of this website is provide our customers and online virtual car sale which 
        anytype of customer can buy their dream vehicle or sell the existing vehicle
        </h3>
       </asp:Label>
</div>

  </form>

</body>

我如何实现上述功能?

感谢您的时间

1 个答案:

答案 0 :(得分:1)

ASPX:

<form id="form1" runat="server">
Language:<br />
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" 
    onselectedindexchanged="DropDownList1_SelectedIndexChanged">
    <asp:ListItem Value="English">English</asp:ListItem>
    <asp:ListItem>Spanish</asp:ListItem>
</asp:DropDownList>
    <div>
    <asp:Label id="eng_lblAboutCM" runat="server" meta:resourcekey="lblAboutCM"><h1>english about :</h1></asp:Label> 
     <asp:Label id="sp_lblAboutCM" runat="server" meta:resourcekey="lblAboutCM"> <h1>spanish about :</h1></asp:Label> 
</div>
<div>   
<asp:Label id="eng_lblContent" runat="server" meta:resourcekey="lblContent"> <h3> english content
    </h3>
</asp:Label>
   <asp:Label id="sp_lblContent" runat="server" meta:resourcekey="lblContent"> <h3> spanish content
    </h3>
   </asp:Label>
   </div>
  </form>

代码背后:

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        ChangeLanguage();
    }
    private void ChangeLanguage()
    {
        foreach (var item in form1.Controls)
        {
            if (item is Label)
            {
                Label lbl = (Label)item;
                lbl.Visible = false;
                if (lbl.ID.StartsWith("eng") &&
                    DropDownList1.SelectedItem.Text == "English")
                {
                    lbl.Visible = true;
                }
                else if (lbl.ID.StartsWith("sp") &&
                    DropDownList1.SelectedItem.Text == "Spanish")
                {
                    lbl.Visible = true;
                }
            }
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ChangeLanguage();
        }
    }