2

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
}
0

4 Answers 4

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/

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

1 Comment

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.
1

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.

3 Comments

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. :)
Thanks Shadow Wizard. I was indeed struggling with the formatting.
Very nice method. After a while looking this is the only answer that helped. Thanks.
1

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.

1 Comment

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.
0

You could inject javascript into your markup using the ClientScriptManager RegisterClientScriptBlock() or RegisterStartupScript() and include your app settings inline or invoke a method and pass the setting as a parameter.

Another approach would be to render a hidden field and include your setting there and then reference it in your javascript code.

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.