Reading AppSettings from javascript

16,551

Solution 1

Common .js files if your including them like this script src="somescript.js" /script are loaded on the clients browser and are never processed on the server.

Only way to load files/values using javascript would be to perform and ajax call to an aspx page that returns either JSON or text..

http://api.jquery.com/jQuery.ajax/

Solution 2

Please note this will only cater for the appSettings section in the web.config

  1. I created an .aspx file called DynamicJs.aspx as below. It will grab the key value pair from the appSettings and construct a JSON string.

    code behind

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Configuration;
    using System.Web.Script.Serialization;
    using System.Collections.Specialized;
    
    public partial class DynamicJs : System.Web.UI.Page
    {
        private string settingsJson = string.Empty;
    
        protected void Page_Load(object sender, EventArgs e)
        {
            NameValueCollection nvc = ConfigurationManager.AppSettings;
            var dict = new Dictionary<string, string>();
            foreach (string key in nvc.Keys)
            {
                dict.Add(key, nvc[key]);
            }
            settingsJson = new JavaScriptSerializer().Serialize(dict);
        }
    
        public string GetSettingsJson() {
            return settingsJson;
        }
    }
    

    HTML (Please note the content type, as it will emit JavaScript)

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="DynamicJs.aspx.cs" Inherits="DynamicJs" ContentType="text/javascript" %>
    
    function GetValue(key){
        var data= <%=GetSettingsJson() %>;
        return data[key];
    }
    
  2. Include the DynamicJs.aspx in the consuming page as below:

    <script src="DynamicJs.aspx" type="text/javascript"></script>
    
  3. Use the following to get value from the configuration

    <script>
        alert(GetValue("key2"));
    </script>
    

It is definitely not the most elegant way of doing this, but I think it will help you achieve what you wanted.

Solution 3

one way to do it is to use a Custom Control page. Add an Web User Control (.ascx) page in your website and put your script code in it

<script type="text/javascript">
    function GetappId() {
        var k = "<%=System.ConfigurationManager.AppSettings["facebookAppID"].ToString(); %>"
        alert(k);
        return k
    }
</script>

now register your control to the page where you want the GetappId function like this

<%@ Register TagPrefix="Scrpt" TagName="GlobalScrpt" Src="~/WebUserControl.ascx" %>

** this tag goes after the <%@ Page %> tag in aspx page

then in the head section of your aspx page call the control like this

<head runat="server">
    <title></title>
    <Scrpt:GlobalScrpt ID="Scrpt1" runat="server" />
</head>

** ensure you have runat="server" in you header tag

now you can call GetappId() and get the desired result anywhere in the aspx page.

update - another solution

another way is to create an aspx (let's say the page is Default1.aspx) page without separate code behind page and place your code there

<%@ Page Language="C#" %>

function GetappId()
{
    var k = "<%=System.ConfigurationManager.AppSettings["facebookAppID"].ToString(); %>";
    alert(k);
}

then in the page where you want to call GetappId add the first aspx page as a javascript page.

<head runat="server">
    <title></title>
    <script type="text/javascript" src="Default1.aspx"></script>
</head>

now call your function anywhere in the page.

Share:
16,551
crichavin
Author by

crichavin

Updated on July 30, 2022

Comments

  • crichavin
    crichavin over 1 year

    I'm trying to create a function that retrieves a web.config app settings value. This works if I put the code alert('<%=ConfigurationManager.AppSettings["facebookAppID"].ToString() %>') in the .ascx file directly. But if I call a common function in a .js file from that .ascx file (so as to have a common global function), it doesn't work...i.e. it doesn't evaluate the value but instead just returns the string "<%=System.ConfigurationManager.AppSettings[\"facebookAppID\"].ToString(); %>"

    Any thoughts as to why this is?

    function GetappId() {
        var k = "<%=System.ConfigurationManager.AppSettings["facebookAppID"].ToString(); %>"
        alert(k);
    return k
    }
    
  • Shadow The Kid Wizard
    Shadow The Kid Wizard about 11 years
    When posting code as part of a list you have to add additional four spaces in every line to have it formatted properly. See my edit. :)
  • Tariqulazam
    Tariqulazam about 11 years
    Thanks Shadow Wizard. I was indeed struggling with the formatting.
  • andleer
    andleer about 11 years
    Interesting approach but I have found that dynamically generating javascript leads to poor maintainability. It is simply better to have static scripts and dynamically generate the calls and pass dynamic data as parameters. Subtle difference but a better separation of concerns. I have a large system built in MVC with all kinds of dynamically generated scripts that are in-lined in views and it is a nightmare. I will never go down that road again.
  • crichavin
    crichavin about 11 years
    This answers my question as to "why" this is happening. Thank you. There are some other great "work arounds" posted here, but at the root of my question was the "why". Thanks to all.
  • Gerard Downes
    Gerard Downes about 10 years
    Very nice method. After a while looking this is the only answer that helped. Thanks.