Open a site by C# browser language

<div class="language">
    <ul>
        <li>
            <asp:LinkButton Text="TR" CausesValidation="false" ID="lnktr_TR" Visible="true" runat="server" OnClick="lnktr_TR_Click"></asp:LinkButton>
        </li>
        <li>
            <asp:LinkButton Text="ENG" CausesValidation="false" ID="lnken_US" Visible="true" runat="server" OnClick="lnken_US_Click"></asp:LinkButton></li>
        <li>
            <asp:LinkButton Text="Беларусь" CausesValidation="false" ID="lnkru_RU" Visible="false" runat="server" OnClick="lnkru_RU_Click" /></li>
        <li>
            <asp:LinkButton Text="العربية" CausesValidation="false" ID="lnkar_AE" Visible="false" runat="server" OnClick="lnkar_AE_Click"></asp:LinkButton></li>
    </ul>
</div>

As you can see above, the language changes with the site button. I want the automatic language to be selected according to the browser language of the site? How can I do it?

Upvotes: 0

Views: 75

Answers (1)

Oguz Ozgul
Oguz Ozgul

Reputation: 7187

Here.

UPDATE: You are executing this in your master page, so the base.UICulture has changed to Page.UICulture.

Also, please not that the use of Page_Load here is just exemplary. Actually, this answer shows how you can read the accept-language header. You should adapt it to your own context. Question: What happens when the customer clicks one of the buttons in your question? Whatever you do there, do in this code also, instead of setting the UICulture.

For Russian, ru-RU and ru;

For Arabic (there are many) but simply ar-AE, or ar

protected void Page_Load(object sender, EventArgs e)
{
    string acceptLangaugeHeader = Request.Headers["accept-language"];
    if (acceptLangaugeHeader != null)
    {
        string[] acceptedLangauges = acceptLangaugeHeader.Split(',');
        foreach (string acceptedLanguageWithQuality in acceptedLangauges)
        {
            string acceptedLanguage = acceptedLanguageWithQuality.Split(';')[0];
            // Check here if it is one of the languages you support:
            switch (acceptedLanguage)
            {
                case "en-US":
                case "en":
                    Page.UICulture = CultureInfo.GetCultureInfo("en-US");
                    break;
                // DO THE SAME FOR OTHER LANGUAGES
                case "tr-TR":
                case "tr":
                default:
                    Page.UICulture = CultureInfo.GetCultureInfo("tr-TR");
                    break;

            }
        }
    }
    else
    {
        Page.UICulture = CultureInfo.GetCultureInfo("tr-TR");
    }
}

Upvotes: 1

Related Questions