Javascript localization in .net

I am trying to determine the best way to implement localization in one of our web applications. This application will have a large number of javascript files that must also be localized.

Localizing .net code is quite simple. We have a file called WebResources.resx that contains all the lines in English (our language back). Then we simply add additional files with alternative localized information (for example: WebResources.es-mx.resx). Then, bam! .Net pretty much takes care of everything else.

Pretty sweet. But when it comes to javascript, not so fast. The MSDN reading they recommend :

You create a separate script file for each supported language and culture. In each script file, you include an object in JSON format that contains the values โ€‹โ€‹of localized resources for this language and culture.

This seems like a nightmare I would like to avoid. Plus, I would like to avoid using asp.net ScriptManager. So I got a bright idea to try using resource files in my .js files. EG foobar.js:

function showGenericError(){
     alert('<% =Resources.WebResources.JsGenericError %>');
}

This, unfortunately, does not work, since .NET does not seem to process .js files. So, the next idea I got is the answer to this thread . He recommended having a javascript file containing all your language strings. This is similar to the waist of resources, because at runtime I need only one language, not all of them.

, . , JSON, , . , .ashx:

public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "application/json";

        StringBuilder json = new StringBuilder();
        using (StringWriter jsonStringWriter = new StringWriter(json))
        {
            using (JsonTextWriter jsonWriter = new JsonTextWriter(jsonStringWriter))
            {
                jsonWriter.WriteStartObject();                

                jsonWriter.WritePropertyName("genericErrorMessage");
                jsonWriter.WriteValue(Resources.WebResources.GenericErrorMessage);

                jsonWriter.WriteEndObject();
            }
        }
        context.Response.Write("var webResources = " + json.ToString());
}

:

<script type="text/javascript" src="js/webResources.js.ashx"></script>

js :

function showGenericError(){
     alert(webResources.genericErrorMessage);
}

, , ? , : ? - ? ? ?

+3
1

, :

javascript

, , .net.

.

0

Source: https://habr.com/ru/post/1792838/


All Articles