web.config variable declaration and use in javascript

953 views Asked by At

How do we define a variable in web.config file and make use of the same in Javascript code?

I made a try assigning key value pair but seems its not working!

2

There are 2 answers

0
Ricconnect On

It is not possible to directly read from the web.config in Javascript. The web.config is only available server side, while Javascript will run client side.

0
Samuel Caillerie On

You should pass the variable from the web.config to the JS file via the code-behind. For example, let's say your variable is named my-variable. Your web.config should be like this :

<configuration>
 <appSettings>
    <add key="my-variable" value="my-value" />
  </appSettings>
</configuration>

Your aspx file can get it and send it to JS like this :

protected void Page_Load(object sender, EventArgs e) {
    ClientScriptManager csm = Page.ClientScript;
    Type cstype = this.GetType();
    string myVariable = ConfigurationManager.AppSettings["my-variable"].ToString();

    // Add a script for the current page just before the end tag </form>
    csm.RegisterStartupScript(cstype, 
        "InitVariable", 
        String.Format("window.myVariable = '{0}';", myVariable, true);
}

And then for any JS, you can use this variable myVariable.