How to use Resources in .js file?

2

I have an Asp.Net MVC project where I am using Resources , and to use it on my web pages p>

@using projeto.Translations

<h3>@Resources.DISPLAY_OLA</h3>

The problem is that I have some items (buttons, for example) that are defined in a .js file, and I need to add the Resources to them as well. How can I do this?

    
asked by anonymous 24.07.2015 / 13:26

2 answers

4

One way is for you to define these strings in your layout, for example in the <head> tag:

<head>
    <script>
        var DISPLAY_OLA = "@Resources.DISPLAY_OLA";
    </script>
</head>

But that is not so elegant. So another way is you create a dynamic external script, as explained in this link , which summarizes:

You create a Resources.js.cshtml view. In this view you create all the resources you need, in the same way as I showed above. Then refer to the script tag:

<script src="@Url.Action("ResourcesJS")"></script>

So with variables declared globally, you can access them in any script. Often it is not recommended to use global variables, but I think in this case it is useful. What you can do is create the resources in a single object (which is how I do it in one of the projects where I work):

var Lang = {
    DISPLAY_OLA: "@Resources.DISPLAY_OLA"
};
Concentrating all resources on the global object Lang you have only one global variable.

    
24.07.2015 / 15:14
1

Hello,

You've already tried something like:

var globalResource = '<%= Resources.MyClass.ResourceKeyValue %>';
    
24.07.2015 / 14:52