How To Access ASP.NET Web.config AppSettings On Client-Side Javascript

Posted by Ahmed Tarek Hasan on 6/21/2014 02:28:00 PM with No comments


You can download the code presented into this post from here


There are many ways by which you can access your ASP.NET web application web.config application settings through your client-side javascript code. The common thing between all of these ways is that to do so you for sure need to access the server-side.

The most proper way I prefer is to load all your application settings in a batch the first time your page is loaded and I think the best practice here is to use a handler to achieve this task. The handler will be responsible for accessing the web.config and retrieving all the application settings keys and their corresponding values and finally returning the response as a javascript file to be loaded once the handler is requested.

This way all what you have to do is to include the handler as a javascript resource on your page or master page then once the page is loaded you will have all your application settings as javascript variables.

Let's have a look on the code below to see what I am talking about.



Web.config
<?xml version="1.0"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
    <system.web>
      <compilation debug="true" targetFramework="4.5" />
      <httpRuntime targetFramework="4.5" />
    </system.web>

  <appSettings>
    <add key="SampleSetting" value="This is the setting value"/>
  </appSettings>
  
</configuration>

ClientGlobalVars.ashx.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using System.Collections.Specialized;

namespace DevelopmentSimplyPut.Handlers
{
    public class ClientGlobalVars : IHttpHandler, IRequiresSessionState 
    {
        public void ProcessRequest(HttpContext context)
        {
			context.Response.ClearHeaders();
			context.Response.ContentType = "application/x-javascript";
			context.Response.Cache.SetCacheability(HttpCacheability.Public);
			context.Response.CacheControl = Convert.ToString(HttpCacheability.Public);
            context.Response.Write("var AppSettings = new Object();\n");

            NameValueCollection appSettings = ConfigurationManager.AppSettings;

            for (int i = 0; i < appSettings.Count; i++)
            {
                string key = appSettings.GetKey(i);
                string value = appSettings.Get(i);
                context.Response.Write(string.Format(CultureInfo.InvariantCulture, "AppSettings.{0} = '{1}';\n", key, value));
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

ClientGlobalVars.ashx
<%@ WebHandler Language="C#" CodeBehind="ClientGlobalVars.ashx.cs" Class="DevelopmentSimplyPut.Handlers.ClientGlobalVars" %>

Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="AccessAppSettingsFromJs.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="/Handlers/ClientGlobalVars.ashx"></script>

    <script>
        alert(AppSettings.SampleSetting);
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    </div>
    </form>
</body>
</html>

So now once you open Default.aspx in a web browser you get the result in the image below.



That's it. You can now access your application settings from client-side javascript.