Wednesday, March 14, 2012

How to read web.config file using JavaScript

 

I have seen many people asking this question in .NET forums. So I thought I will share this small piece of code.

First we will see web.config entry which we are going to read,

<configuration>
      <appSettings>
            <addkey="WordTemplate"value="template.doc"/>
      </appSettings>
      <connectionStrings>
                 <add name="MysqlCon"
         connectionString="server=1xx.1xx.x.x;User Id=username;password=password;database=dbName;Persist Security Info=True"
         providerName="MySql.Data.MySqlClient" />
   </connectionStrings>
      </connectionStrings>
...
<configuration>

Now we will see the JavaScript function which reads above connection string and the AppSettings key,

<script language="javascript" type ="text/javascript"> 
function ReadWebConfig()
{
    var strCon = '<%=ConfigurationManager.ConnectionStrings["MysqlCon"].ConnectionString %>'
    alert(strCon);
    var strTemp = '<%=ConfigurationManager.AppSettings["WordTemplate"].ToString() %>'
    alert(strTemp);
}
</script>

1 comment:

Unknown said...
This comment has been removed by the author.