To streamline the retrieval of environmental parameters for use in various JS objects, I developed a handler like the one below:
/Environment.ashx/.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcApplication2
{
/// <summary>
/// Summary description for $codebehindclassname$
/// </summary>
public class Environment : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/javascript";
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.Cache.SetExpires(DateTime.Now.AddSeconds(600));
context.Response.Write(String.Format("Environment = {{ RootPath:\"{0}\" }};", context.Request.ApplicationPath)); // set any application info you need here
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
Do not forget to enable the handler in your web.config:
<configuration>
<system.web>
<httpHandlers>
<!-- ... -->
<add verb="*" path="environment.ashx" validate="false" type="MvcApplication2.Environment, MvcApplication2"/>
</httpHandlers>
</system.web>
Next, make sure to include the handler in your master or content ASPX page (assuming ASP.NET MVC):
<html>
<head>
<!-- include other necessary JS files and resources here -->
<script src="<%=Url.Content("~/environment.ashx"); %>" type="text/javascript"></script>
</configuration>
</head>
</html>
Now, with Environment.ashx loaded, you can easily reference Environment.RootPath in all JS objects and scripts:
var imagePath = Environment.RootPath + "images/image.jpg";