Introduction
This is my first tip on CodeProject.
In this tip, I discuss how to create dynamic JavaScript file in json format for Global Resource Files (.resx) in ASP.NET. (Sample code is given For ASP.NET MVC but you can also utilize in classic ASP.NET applications.)
Using the Code
Let's start..............
First, create 1 Resource file in our Application Name: "Resource.resx" in App_GlobalResources folder.
Create the following method in any controller. (You can also use HomeController
).
public JavaScriptResult GlobalResourceJSCreate()
{
return ResourceSerialiser.GetResourceScript(Resource.ResourceManager);
}
Where Resource is my Resource.resx file in App_GlobalResources Directory we created. Now we need ResourceSerialiser Class
for GetResourceScript
method to execute.
namespace ProjectName
{
public static class ResourceSerialiser
{
public static JavaScriptResult GetResourceScript(ResourceManager resourceManager)
{
string cacheName = string.Format
("ResourceJavaScripter.{0}", CultureInfo.CurrentCulture.Name);
JavaScriptResult value = HttpRuntime.Cache.Get(cacheName) as JavaScriptResult;
if (value == null)
{
JavaScriptResult javaScriptResult = CreateResourceScript(resourceManager);
HttpContext.Current.Cache.Insert(cacheName, javaScriptResult);
return javaScriptResult;
}
return value;
}
static JavaScriptResult CreateResourceScript(ResourceManager resourceManager)
{
ResourceSet defaultSet = resourceManager.GetResourceSet
(CultureInfo.GetCultureInfo("en"), true, true);
ResourceSet resourceSet = resourceManager.GetResourceSet
(CultureInfo.CurrentCulture, true, true);
var resourceBaseName = resourceManager.BaseName;
var jsonObjectName = resourceBaseName.Substring(resourceBaseName.LastIndexOf(".") + 1);
StringBuilder sb = new StringBuilder();
sb.Append(jsonObjectName);
sb.Append("={");
foreach (DictionaryEntry dictionaryEntry in resourceSet)
if (dictionaryEntry.Value is string)
{
string value = resourceSet.GetString
((string)dictionaryEntry.Key) ?? (string)dictionaryEntry.Value;
sb.AppendFormat("\"{0}\":\
"{1}\",", dictionaryEntry.Key, EncodeValue(value));
}
string script = sb.ToString();
if (!string.IsNullOrEmpty(script))
script = script.Remove(script.Length - 1);
script += "};";
JavaScriptResult result = new JavaScriptResult { Script = script };
return result;
}
static string EncodeValue(string value)
{
value = (value).Replace("\"", "\\\"").Replace('{', '[').Replace('}', ']');
value = value.Trim();
value = System.Text.RegularExpressions.Regex.Replace(value, @"\s", " ");
return value;
}
}
}
Now add the below line to the RegisterRoutes
method located in the Global.asax.cs file in our application.
This creates a JS file in the
root directory.
routes.MapRoute("JSFileName", "JSFileName.js",
new { controller = "Home", action = "GlobalResourceJSCreate" });
E.g.:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("JSFileName", "JSFileName.js",
new { controller = "Home", action = "GlobalResourceJSCreate" });
routes.MapRoute(
"Default", "{controller}/{action}/{id}", new { controller = "Home",
action = "Index", id = UrlParameter.Optional } );
}
Now we need to add Url to
our master page so we can use Global Resource File key value combination in JS file as
below:
<script src="<%= ConfigurationManager.AppSettings["AppUrl"]
%>/JSFileName.js" type="text/javascript"></script>
In our JS file, we can access as below:
var str = Resources.Resource.lblFormulaName;
Where lblFormulaName
is Name
in "Resource.resx"
file and above statement returns Value "Formula Name".