Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Read Configuration Settings of Web.config using Javascript

3.43/5 (6 votes)
30 Apr 2010CPOL1 min read 116.9K  
Web.config is the main settings and configuration file for an ASP.NET web application. The file is an XML document that defines configuration information regarding the web application. The web.config file contains information that control module loading, security configuration, session state...
Web.config is the main settings and configuration file for an ASP.NET web application. The file is an XML document that defines configuration information regarding the web application. The web.config file contains information that control module loading, security configuration, session state configuration, and application language and compilation settings. Web.config files can also contain application specific items such as database connection strings.

The below method is used to access non-secure keys/values in the web.config don't use it to access secure sections as the ConnectionString for example, because the value will be rendered in the html of the page.


Example 1:
XML
<!-- This is an example Web.config file -->
<configuration>
    <appSettings>
            <add key="var1" value="SomeValue"/>
      </appSettings>
<configuration>


In this article, we will see how to read the configuration settings in the web.config using ‘javascript’.

Step 1: Create a new ASP.NET website. Add a button control to the Default.aspx.

Step 2: Right click the project > Add New Item > Web Configuration File
Add the following sample entry to the appSettings section in the web.config between the <configuration> tag as shown in the example 1:
XML
<add key="var1" value="SomeValue"/>


Step 3: To read these entries using javascript, add the following script in the <head> tag of your Default.aspx page as shown below:

XML
<head runat="server">
    <title></title>
    <script type="text/javascript">
    function ReadConfigurationSettings()
    {
        var k = '<%=ConfigurationManager.AppSettings["var1"].ToString() %>'
        alert(k);
    }
    </script>
</head>


Step 4: Call this function on a button click and display the values of the configuration settings:
<input type="button" value="Get" onclick="ReadConfigurationSettings();" />



You can update this code to read any section in the web.config.
Now Run the application and click the button. The value of the key "var1" in the appSettings will be displayed in the alert window.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)