Sunday, 25 September 2016

How to create multilingual application in C# ?

Firstly defined In global.asax.cs

 protected void Application_BeginRequest()
        {
            CultureInfo info = new CultureInfo(System.Threading.Thread.CurrentThread.CurrentCulture.ToString());
            info.DateTimeFormat.ShortDatePattern = "dd.MM.yyyy";
            System.Threading.Thread.CurrentThread.CurrentCulture = info;
        }


        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies["lang"];
            if (cookie != null && cookie.Value != null)
            {
                System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(cookie.Value);
            }
            else
            {
                System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en");
            }
        }

In App_Global_ResourceFile folder


To create a resource file in this folder -:
default.
employee.resx (It's automatic in English language we represent string and value)

Emp  Employee

employee.bn.resx (bn means bengali language we represent string and value)

Emp Employee_bn

We represent View Pages



In LayOut Pages defined-

    <script type="text/javascript">
        function SetLanguage(obj) {
            debugger;
            $.ajax({
                cache: false,
                type: "GET",
                url: '/Home/SetCulture/?lang=' + obj,
                success: function (result) {
                    debugger;
                    window.location.reload();

                },
                error: function (result) {
                    alert("Error");
                }
            });
        }

    </script>

 public ActionResult SetCulture(string lang)
        {
            LanguageModel model = new LanguageModel();
            if (!String.IsNullOrEmpty(lang))
            {
                string culture = lang;
                CultureInfo ci = CultureInfo.GetCultureInfo(culture);
                Thread.CurrentThread.CurrentUICulture = ci;
                model.Culture = lang;
                Response.Cookies["lang"].Value = culture;
                Response.Cookies["lang"].Expires = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, INDIAN_ZONE).AddDays(30);
            }
            else
            {
                string culture = "en";
                CultureInfo ci = CultureInfo.GetCultureInfo(culture);
                Thread.CurrentThread.CurrentUICulture = ci;
                model.Culture = culture;
                Response.Cookies["lang"].Value = culture;
            }
            return Json(model, JsonRequestBehavior.AllowGet);

        }

<label>App_GlobalResources.employee.Emp</label>