You may wish to expose server side configuration via JavaScript. For example, you may have a different base url for your REST api per environment (dev,test,uat,prod) which your JavaScript AJAX calls need to consider.
Typically, you would push the configuration data down via an html5 data- attribute, a hidden input field or via explicit assignment to a JavaScript global. You usually end up doing this for every item you wish to expose. However, using a custom MVC ActionFilterAttribute and a Server-to-JSON serialization technique you can easily expose your web.config appSettings for controller actions.
NOTE: Exposing the entire appSettings configuration section may expose your application to security risks.
To start with read through this technique to serialize the ViewBag into a namespaced JavaScript global - Transferring Server data to JavaScript with initial Page Request.
Make sure you have an appSettings section in your web.config file.
<appSettings>
<add key="foo" value="bar" />
</appSettings>
Next, create a custom ActionFilterAttribute to read in the web.config appSettings and attach to the ViewBag.
/// <summary>
/// Add web.config app settings into the ViewBag so pages can utilize it for JS etc.
/// </summary>
public class AppSettingsAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
var viewResult = filterContext.Result as ViewResult;
if (viewResult == null)
return;
viewResult.ViewBag.AppSettings = ConfigurationManager.AppSettings.AllKeys.ToDictionary(key => key, key => ConfigurationManager.AppSettings[key]);
base.OnActionExecuted(filterContext);
}
}
NOTE: The AppSettings is a NameValueCollection which is a List/Array - not a Dictionary. When the NameValueCollection is serialized to JSON it comes out as an array notation - not object notation - see http://stackoverflow.com/q/7003740
Next we need to apply this attribute to controllers/actions where you wish the appSettings to be made available via JavaScript:
[AppSettings]
public class ConfigurationController : Controller
{
public ActionResult Index()
{
return View();
}
}
Now you can access the appSettings data from your JavaScript.
var appSettings = application.viewbag.appSettings;
alert(appSettings["foo"]);
You'll need to NuGet the Newtonsoft.Json library.
Serialize, ViewModel, Knockout, JavaScript, ViewBag, Model, AJAX, Web.Config, AppSettings