Reading web.config values ​​from Javascript

I want to read application key from web.config file through java script. Web.config key to read

<appSettings> <add key="Key1" value="value1" /> <appSettings> 

I include the following inside my java script function.

 function Evaluate() { var key = '<%=ConfigurationManager.AppSettings["Key1"].ToString() %>'; alert(key); } 

However, in the end, I get <%=ConfigurationManager.AppSettings["Key1"].ToString() %> in the message.

What am I missing?

+4
source share
3 answers

The <%= => will only be executed if it is in the .aspx file. If you put it in a .js file, then it will look like any other text. For your code to work, the javascript you submitted must be embedded in the .aspx file.

+13
source

After placing the values ​​in the configuration file on the page that you will use, enter the java script as follows: you will access the value in the java script as global, do not necessarily declare it.

in web configuration:

  </appSettings> <add key="varName" value="1" /> </appSettings> 

on the html page:

 <script> var varName= '@System.Configuration.ConfigurationManager.AppSettings["varName"]'; </script> 
+2
source

Using regular js, you can use this in your layout.htmlcs, at the beginning:

  @{ <script> sessionStorage.setItem("ProductionHostURL", '@System.Configuration.ConfigurationManager.AppSettings["ProductionHostURL"]'); </script> } <!DOCTYPE html> 

Then in your main js file layout.htmlcs you can use this method similar to this:

 var urlBaseProduction; var urlBaseDevelopment; $(document).ready(function () { configureHostEnvironment() .... } 

In this method, configure the variables for use in production and development, for example:

 function configureHostEnvironment(){ HOST = sessionStorage.getItem("ProductionHostURL") if (HOST.length <= 0) { alert("Host not configured correctly") } else { urlBaseProduction= host + '/api/'; urlBaseDevelopment= host + port + '/api/'; } } 

If you have a suggestion or improvement on this method, please comment.

0
source

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


All Articles