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

PeterFromCologne picture PeterFromCologne · Jun 24, 2011 · Viewed 20.9k times · Source

We are building large ASP.NET applications for the intranet use in multiple languages/cultures. We utilize the Globalization with RESX files and use GetResourceText on the server side to get the localized texts.

Lately we are doing more and more client side logic with JQuery.

How do I get the RESX texts to be used in Javascript?

  • e.g. texts used for validation, dynamic messages etc.

All our Javascripts are in .JS files, we do not want to mix HTML in the ASPX page and Javascript blocks.

Thanks for your help.

Answer

Deano picture Deano · Jun 28, 2011

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