How to use Resources in . js file?

Asked

Viewed 298 times

3

I have a project Asp.Net MVC where I’m wearing Resources, and to use it in my web pages it’s easy!

@using projeto.Translations

<h3>@Resources.DISPLAY_OLA</h3>

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

3 answers

5


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

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

But that’s not so elegant. So another way is you create a dynamic external script, as explained at that link, that summing up:

You create a view Resources.js.cshtml. In this view you create all the Resources you need, just like I showed above. Then reference in the script tag:

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

Thus, with variables declared globally, you can access them in any script. It is often not recommended to use global variables, but I think in this case it is useful. What can be done is to create the Resources in a single object (which is how I do 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.

1

Hello,

you’ve tried something like:

var globalResource = '<%= Resources.MyClass.ResourceKeyValue %>';
  • Yes friend, but the variable content takes the string literally (as it is written in front of it) .

0

You can create a label and assign text something like

text='<%= Resources.MyClass.ResourceKeyValue %>'

Or for example...

<dx:ASPxLabel ID="myLabel" runat="server" Text="<%$ Resources:TextResource,  SuaPalavra %>" />

Browser other questions tagged

You are not signed in. Login or sign up in order to post.