6

I want to read an app key from the web.config file via java script. The web.config key to be 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, I end up getting <%=ConfigurationManager.AppSettings["Key1"].ToString() %> in the alert.

What am i missing?

3
  • 1
    Your JS code is not being processed by the ASP engine. Where are you putting it? Commented Jul 17, 2013 at 22:07
  • bfavaretto is right. You could define a javascript variable in your ASPX containing the value you need. Commented Jul 17, 2013 at 22:08
  • I am putting it inside an external javascript file . The link to this file is given inside the webform.aspx page as <script type='text/javascript' src='script.js' /> Should I only include it inside the aspx page itself? Commented Jul 17, 2013 at 22:08

2 Answers 2

14

The <%= => tag is only going to execute if it is within a .aspx file. If you place it within a .js file, then it will just be like any other text. In order for your code to work, the javascript you posted would have to be embedded within the .aspx file.

Sign up to request clarification or add additional context in comments.

3 Comments

Ok, so Let's say I create a global variable inside my aspx page as <script type="text/javascript"> var key1 = '<%=ConfigurationManager.AppSettings["key1"].ToString() %>'</script>. Is there a way I can access key1 from my external javascript file? I do not want to embed the entire function code in my aspx page.
Yes, you should be able to access it from the external javascript file. Don't include var if you want the variable to be truly global. <script type="text/javascript"> key1 = <%=ConfigurationManager.AppSettings["key1"].ToString() %>'</script>
on the web.Config: </appSettings> <add key="varName" value="1" /> </appSettings> On the html page: <script> var varName= '@System.Configuration.ConfigurationManager.AppSettings["varName"]'; </script>
5

After to put the values on the config file, on the page that you will use the value put the java script this way bellow: You will access the value in the java script as a global, not necessary to declare it.

on the web config:

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

on the html page:

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

2 Comments

How can I convert varName in a List<string> if I don't know how many key are present in appSettings ?
There is a typo in the first appSettings tag. remove the slash.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.