jfamvg
jfamvg

Reputation: 237

Using server side resources in JavaScript

I am updating my ASP.NET project to use some more JavaScript and AJAX. I’ve refactored parts of my HTML so that they are created with JavaScript, but now I’m not able to use the values of my local resource files anymore.

The structure of my project is that each page/usercontrol has it’s own set of local resources and it’s own set of .js files.

Is there a simple/elegant solution to use the local resources in JavaScript? Preferably I would like to see something that takes the myfile.js file, parses it by looking at the current language, and outputs something myfile.en.js

UPDATE

How I’d like to work:

<script src="../message.js"></script>
function showMessage(){
alert(GetLocalResource("AlertMessage"));
}

Upvotes: 2

Views: 954

Answers (3)

Tys
Tys

Reputation: 3610

Here is an example on how to write your own Http Handler to create minified JavaScript on the fly. Perhaps you can extend this with translation options and output not only minified, but also translated files.

http://weboptimizer.codeplex.com/

Upvotes: 0

Mat&#237;as Fidemraizer
Mat&#237;as Fidemraizer

Reputation: 64923

In my case, I found that converting RESX files into JSON files and then loading them in the client-side JavaScript works good.

Since RESX is XML, using LINQ-to-XML you'll convert each node into a key and each value into the key value:

{ "myLabel": "hello world!" }

Now the problem will be loading the right resources for user's culture. If you use a convention like RESX and files are called like MyResources.en-US.json, if you write a cookie with current user's culture, it's just about concatenating it as follows: "MyResources." + cultureCookieValue + ".json"

Finally, you might use jQuery to load the whole resources:

$.getJSON("/JsonResources/MyResources." + cultureCookieValue + .json").done(function(resources) {

  var myLabel = resources.myLabel;
});

This is just the idea. Now, if you develop it, you may create some abstractions so your client-side code can access such resources using this approach.

Suggestion: You can convert RESX on build using MSBuild!

Upvotes: 2

Patrick Hofman
Patrick Hofman

Reputation: 156968

Yes. Create an Controller, or ApiController that reads the resources from your folder or resx file.

To read from a resx file, use ResourceManager

There are plenty examples online for the general structure. Like this one: Display image from database in asp mvc. Of course, you could use this not only for images, but any type of file.

You can map an incoming parameter, like filename the way you want, and you can post-process it to replace things if you need to. You can also set some HTTP headers to handle caching.

Upvotes: 2

Related Questions