简体   繁体   中英

Using resource files (.resx) in javascript

I'm trying to use localization in my project but I can't find a way to access my resx files from javascript. I have been looking around a bit and I don't think the 'AJAX call' method would be ideal for my project since I have quiet a lot of string that need to be fetched and it would just have to spam the server hard!

if I just put it in my HTML then it works with this code:

@using Resources
<p>@Html.Raw(ISt_Localization.January)</p>

I guess one of the things I could do is put all the strings in a hidden div and then get the content from the divs in my javascript but this wouldn't be very effective..

I had a similar situation and in my case, I created a separate partial view which only contained a javascript block where I put all the resource strings required for use in client side logic. Every resource string was defined as a javascript variable. You could also create an associative array.

In your partial view:

var Resources = {
        January : "@Html.Raw(ISt_Localization.January)",
        February : "@Html.Raw(ISt_Localization.February)",
        ...
};

You can also try the below thing directly

@using Resources

<script>
var value = '@Resource.January';
/* work with value 
.......
.....

*/
</script>

I took a totally different approach.

I want to have the resource strings required by my Javascript files be part of my resx files.

Every key in my resource file which starts with js has to become available in Javascript.

In global.asax, in Application_OnStart I build Javascript files for all supported languages on the fly. Because this only happens at the start of the application, it does not matter if it takes a few seconds.

Advantages:

  • All translations in one place (in the rex files which you use for your .NET application (C# or VB), but also for your Javascript code
  • Always up to date
  • Very fast, because we are going to use variables to get the translations

Building the Javascript file is easy. Iterate through all key value pairs in all resx-files. Just pick out the keys starting with _js_ . Save the key value pair in the Javascript file.

So if the key value pair in the resx-file (languageSupport_es.resx) is '_js_Hello', 'Hola', I write in my Javascript file (languageSupport_es.js) var Hello = 'Hola';

So alert(Hello) will give you 'Hola' if the current language is Spanish.

The only thing I now have to take care of, is using the right 'language Javascript file' is loaded before my other Javascript files. So if the language is Spanish, I ONLY include my 'Spanish language Javascript file' (languageSupport_es.js) first.

Easy no? If somebody is interested, I can show some example code...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM