Pages

Friday, November 11, 2011

Read Configuration Settings of Web.config using Javascript


Web.config is a XML file containing the configuration settings of our application. Amongst its other uses, the file is extremely handy when it comes to changing configuration settings of an application, even when the application is live. You can define your own specific application settings, such as a database connection string using the <appSettings> tag and read and write values to the file programmatically. In this article, we see how to read the configuration settings in the web.config using ‘JavaScript’.
In one of the previous articles, we saw how we can use the API’s in the System.Configuration and System.Web.Configuration namespaces to read and write configuration settings in the web.config. In this short article, we will see how we can retrieve the values from the  <appSettings> and <connectionStrings> section in the web.config using JavaScript. So let us get started.
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 entries in the file between the <configuration> tag as shown below:
<configuration>
      <appSettings>
            <addkey="var1"value="SomeValue"/>
      </appSettings>
      <connectionStrings>
            <addname="MyConnString"connectionString="Data Source=(local);Initial Catalog=Northwind;Integrated Security=True;"/>
      </connectionStrings>
...
<configuration>
 
Step 3: We will now read these entries using JavaScript. To do so, add the following script in the <head> tag of your Default.aspx page as shown below:
<head runat="server">
    <title>Read Config Entries Using Javascript</title>
    <script type="text/javascript">
    function ReadConfigSettings()
    {
        var conn = '<%=ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString %>'
        alert(conn);
        var v1 = '<%=ConfigurationManager.AppSettings["var1"].ToString() %>'
        alert(v1);
    }
    </script>
</head>
Step 4: Call this function on a button click and display the values of the configuration settings
   <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="ReadConfigSettings()" /></div>
 
That’s it. Run the application and click the button. The values of the configuration settings in the web.config will be displayed in the alert boxes.
I would like to thank JRICE from the ASP.NET forums for this tip.
I hope you liked this short article and I thank you for viewing it.

No comments:

Post a Comment