Localize Strings in Javascript

前端 未结 12 1483
长发绾君心
长发绾君心 2020-11-28 05:52

I\'m currently using .resx files to manage my server side resources for .NET.

the application that I am dealing with also allows developers to plugin Ja

12条回答
  •  渐次进展
    2020-11-28 06:17

    We use MVC and have simply created a controller action to return a localized string. We maintain the user's culture in session and set the thread culture before any call to retrieve a language string, AJAX or otherwise. This means we always return a localized string.

    I'll admit, it isn't the most efficient method but getting a localised string in javascript is seldom required as most localization is done in our partial views.

    Global.asax.cs

    protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
    {
        if (Context.Handler is IRequiresSessionState || Context.Handler is IReadOnlySessionState)
        {
            // Set the current thread's culture
            var culture = (CultureInfo)Session["CultureInfo"];
            if (culture != null)
            {
                Thread.CurrentThread.CurrentCulture = culture;
                Thread.CurrentThread.CurrentUICulture = culture;
            }
        }
    }
    

    Controller Action

    public string GetString(string key)
    {
        return Language.ResourceManager.GetString(key);
    }
    

    Javascript

    /*
        Retrieve a localized language string given a lookup key.
        Example use:
          var str = language.getString('MyString');
    */
    var language = new function () {
        this.getString = function (key) {
            var retVal = '';
            $.ajax({
                url: rootUrl + 'Language/GetString?key=' + key,
                async: false,
                success: function (results) {
                    retVal = results;
                }
            });
            return retVal;
        }
    };
    

提交回复
热议问题