How to get line from .resx file to .js file

I want to show a warning message in two different languages. I am using asp.net App_GlobalResources . Can I use it in a script.js file?

+6
source share
3 answers

You cannot directly access resources in a RESX file from javascript files.

However, you can create a partial view (in case you use MVC) from which you can access all of these resources. After that, you can enable this partial inside your pages.

For example, you can do a partial in which you will have:

<script> var Resources = { Name: '@Resources.tags.Name', Surname: '@Resources.tags.Surname', }; </script> 

After that, you can include this page on the pages you need and access javascript from these resources using:

 Resources.Name 

If you are not using MVC, let me know to learn how to do this in ASP.NET.

If you have any doubts, please tell me.

For WebForms

If you use WebForms, you can use a user control in which you will configure javascript for input on the page.

Then include this user control on your page (preferably a wizard to make it accessible across your entire site), and you can access it.

The user control will look like this:

 public partial class resources : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { LiteralControl jsResource = new LiteralControl(); jsResource.Text = "<script type=\"text/javascript\">"; jsResource.Text += "var Resources = {"; jsResource.Text += "Name: '" + Resources.Resource.Name + "',"; jsResource.Text += "Surname: '" + Resources.Resource.Surname + "',"; jsResource.Text += "};"; jsResource.Text += "</script>"; Page.Header.Controls.Add(jsResource); } } 

Then you would include this control on your page:

 <uc1:resources runat="server" ID="resources" /> 

And you can just access your javascript by doing this:

 <script> alert(Resources.Name); alert(Resources.Surname); </script> 
+6
source

A quick method is that you can pre-set the values ​​of the Javascript variable in the aspx file.

 <script type="text/javascript"> var alertMessage = '<%=Resources.YourResourceFile.alertMessage%>'; ... ... alert(alertMessage); </script> 

This displays the value of the resource in the alertMessage variable, and you can use it where necessary.

- Page You can also use all the variables of the resource file on the client side using

 <script type="text/javascript"> var resources_en = { welcome_en : '<%= Resources.testResources_en.Welcome %>' } alert(welcome_en); </script> 

Add all the necessary resource variables to resource_en to access them on the client.

+1
source

Try the following:

Its very simple

 <script type="text/javascript"> var resources_en = { welcome_en : '<%= HttpContext.GetGlobalResourceObject("ResourceFileName", "yourMsg") %>'; } alert(welcome_en); </script> 
0
source

Source: https://habr.com/ru/post/977112/


All Articles