-1

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
  • Could you show us some code as to how you've tried to assign it? Commented Nov 19, 2014 at 10:25
  • possible duplicate of Reading web.config from JavaScript Commented Feb 26, 2015 at 13:51

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.