Click here to Skip to main content
Click here to Skip to main content

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

, 3 Jan 2014
Rate this:
Please Sign up or sign in to vote.
Global Resorce File Creation in json Format using ASP.NET

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
{ 
    /// <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();
            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", // 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 lblFormulaName is Name in "Resource.resx" file and above statement returns Value "Formula Name".

License

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

About the Author

Kiran mochi
Software Developer at ITMC soft india pvt 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.
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 3 Jan 2014
Article Copyright 2014 by Kiran mochi
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid