How to get texts from Resx to be used in Javascript? How to get texts from Resx to be used in Javascript? asp.net asp.net

How to get texts from Resx to be used in Javascript?


Unfortunately, in an external JS file the server side code is not being processed by the server. However I have seen a workaround where you can set your translated values in hidden fields on the page - this way your javascript will be able to read the values in.

For example:

 <%-- This goes into your page --%> <input type="hidden" id="translatedField" name="translatedField" value="<%=Resources.Resources.translatedText %>" />

and use this inside your javascript file:

 // This is the js file $(document).ready(function() {  alert($("#translatedField").attr("value")); });

You will be able to separate the values and still see it in your external JS file.

There is also another workaround that creates a .aspx file that only outputs Javascript instead of HTML. Check out the link below:

Using server side method in an external JavaScript file


Always separate functionality from human readable strings.

If you're creating jQuery-plugins you should be able to pass an array of localized strings as parameter when you call your different jQuery functions. The array could be defined as inline javascript directly on the page calling the different jQuery plugins or you could load the from external resource in the format /scripts/localization/strings.js?ci=en-US and register a Generic ASP.Net Handler in web.config that would respond to scripts/localization/strings.js

The DatePicker control is a fine example of how to localize text for the jQuery datepick control - this js file is dynamically created from resource files (resx) and when included on a page it will make sure the calendar control will have danish text.


Create a HttpHandler (.ashx file), and return JSON with your text resource strings.

You may also "publish" it to global namespace, i.e.

Response.Write("window.Resources=");Response.Write((new JavaScriptSerializer()).Serialize(strings));

set up HTML like:

<script src="Resx.ashx?lang=en-US" /><button class="LogoutButtonResourceId OtherButtonClasses">(generic logout text)</button><a href="#"><span class="SomeLinkTextResourceId OtherClasses">     (generic link text)</span></a>

and apply texts like this:

$(document).ready(function() {  for(var resId in Resources){    $("."+resId).html(Resources[resId]);   }});