Dennis
Dennis

Reputation: 21

javascript issue with web.config

trying to access web.config file using js and .net, and get the "error.html?aspxerrorpath=/testing2.aspx" error page.

<%@ Page Language="C#" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>

<script type="text/javascript" runat="server">

    function ReadConfigSettings()
    {

       var v1 = '<%= ConfigurationManager.AppSettings["var1"].ToString() %>'
       alert(v1);

    }
</script>

</head>
<body>
    <form id="form1" runat="server">
   <div><asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="ReadConfigSettings()" /></div>
    </form>
</body>
</html>

Upvotes: 0

Views: 398

Answers (2)

rsbarro
rsbarro

Reputation: 27349

Your code example will throw an exception if there is no "var1" defined in the appSettings section.

You could try this instead:

<%= ConfigurationManager.AppSettings["var1"] %>

That statement will handle the case where "var1" is not defined.

To define the appSetting, you should have something like this in your web.config:

<configuration>
   ...
   <appSettings>
      <add key="var1" value="test" />
   </appSettings>
   ...
</configuration>

Upvotes: 1

Josh
Josh

Reputation: 44916

As rsbarro explained already, your code is probably throwing an exception due to the absence of that setting.

Now, I'm not sure exactly what you are trying to accomplish however. The title of your post, and the code samples seem to indicate you want to extract some value from the config file whenever you click the button. However, that isn't what is happening here.

Remember that anything between <% %> gets evaluated on the server. So before you page ever gets rendered, it will attempt to run that code and embed it into the response as indicated by you. In the end you will get a static value embeded in your script.

<script type="text/javascript" runat="server">

    function ReadConfigSettings()
    {

       var v1 = 'MyStaticValue'; //This was rendered on the server
       alert(v1);

    }
</script>

If you want to do something more than this, then you will have to do this via AJAX. You have a couple of options here:

  1. Create a web service (.asmx, or WCF)
  2. Use Page Methods
  3. Use UpdatePanel

Upvotes: 1

Related Questions