Click here to Skip to main content
14,297,726 members

Create a Dynamic JavaScript File for Global Resorce File Creation in JS Format Using ASP.NET MVC

Rate this:
4.29 (4 votes)
Please Sign up or sign in to vote.
4.29 (4 votes)
3 Jan 2014CPOL
Global Resorce File Creation in json Format using ASP.NET


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
    /// <summary>
    /// Utility class that allows serialisation of .NET resource files (.resx)
    /// into different formats
    /// </summary>
    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();
            foreach (DictionaryEntry dictionaryEntry in resourceSet)
                if (dictionaryEntry.Value is string)
                    string value = resourceSet.GetString
                    ((string)dictionaryEntry.Key) ?? (string)dictionaryEntry.Value;
                    "{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" });   


public static void RegisterRoutes(RouteCollection routes)
  routes.MapRoute("JSFileName", "JSFileName.js", 
  new { controller = "Home", action = "GlobalResourceJSCreate" });
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", 
            action = "Index", id = UrlParameter.Optional } // Parameter defaults

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 <code>lblFormulaName is Name in "Resource.resx" file and above statement returns Value "Formula Name".


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Kirankumar Chauhan
Software Developer at Infosys ltd.
India India
Kiran is from India. He started his programming career with C and C++. After programming C/C++ for 2 years during his graduation he discovered his favorite programming language C#. He is working as software engineer at ITMC soft india pvt ltd. He is using Javascript, Jquery, HTML5, Asp.Net(Classic),Asp.Net MVC to develop applications or programs.

Comments and Discussions

SuggestionNice tip, but didn't work for me... Pin
Karim B.27-Aug-14 5:24
memberKarim B.27-Aug-14 5:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Posted 3 Jan 2014


6 bookmarked