Click here to Skip to main content
15,861,168 members
Articles / Web Development / HTML

Resource File to JavaScript Object

Rate me:
Please Sign up or sign in to vote.
4.77/5 (14 votes)
23 Feb 2011CPOL1 min read 76.3K   751   25   16
A web control that creates a JavaScript object representing a resx (resources) file and makes it available to be used from HTML and JavaScript code.

Introduction

This is an ASP.NET control that can be dragged to a webpage or user control. It registers a JavaScript block to the page, which contains an object that represents the contents of a resx (resource) file (key and value). This is useful to get resource strings from JavaScript code (client side).

Background

It is known that getting resource strings in client-side JavaScript is not straightforward. This control makes it easy to share the same server side resource files (resx files) in client side code.

Using the Code

This web control will write all the entries in the specified resx file to a JavaScript (client side) object. So please make sure that the resx file entries don't contain sensitive data and the number of the entries in the resx file is not too large.

The code contains two classes, ResourcesToJavaScriptBase and GlobalResourcesToJavaScript. ResourcesToJavaScriptBase acts as an abstract base class that contains the logic of the idea. GlobalResourcesToJavaScript is a concrete class that specializes the logic to handle global resources (in the App_GlobalResources folder).

Note: If the resource key contains a dot (.), it will be replaced by an underscore (_). Example: textBox1.Text will be converted to textBox1_Text in the JavaScript object.

ResourcesToJavaScriptBase
C#
/// <summary>
/// Represents a class that can be used to render
/// a JavaScript object that contains resource keys and values
/// of a specific resX file dependant on the CurrentUI culture.
/// </summary>
public abstract class ResourcesToJavaScriptBase : Control
{
    /// <summary>
    /// Gets the full resX file path.
    /// </summary>
    /// <returns></returns>
    protected abstract string GetResXFilePath();
 
    /// <summary>
    /// Sets and Gets the generated JavaScript object name.
    /// </summary>
    public abstract string JavaScriptObjectName
    {
        get;
        set;
    }
 
    /// <summary>
    /// Get the resource value of specific key
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    protected abstract string GetResourceValue(string key);
 
    protected virtual void ValidateBeforeRender(System.Web.UI.HtmlTextWriter writer)
    {
        if (!File.Exists(GetResXFilePath()))
        {
            writer.Write("GlobalResourcesToJavaScript: " + this.ClientID + 
                         ": Can't find the file " + GetResXFilePath());
            return;
        }
        return;
    }
   
    protected override void OnLoad(EventArgs e)
    {
        if (!string.IsNullOrEmpty(JavaScriptObjectName) && 
             File.Exists(GetResXFilePath()) && 
             !Page.ClientScript.IsClientScriptBlockRegistered(
             GetType(), JavaScriptObjectName))
        {
            StringBuilder script = new StringBuilder();
            script.Append("<script type=\"text/javascript\"> ");
            using (System.Resources.ResXResourceReader resourceReader = 
                   new System.Resources.ResXResourceReader(GetResXFilePath()))
            {
                script.Append(" var " + JavaScriptObjectName + " = { ");
                bool first = true;
                foreach (DictionaryEntry entry in resourceReader)
                {
                    if (first)
                        first = false;
                    else
                        script.Append(" , ");
 
                    script.Append(NormalizeVariableName(entry.Key as string));
                    script.Append(":");
                    script.Append("'" + GetResourceValue(entry.Key as string) + "'");
                }
                script.Append(" }; </script>");
                Page.ClientScript.RegisterClientScriptBlock(GetType(), 
                     JavaScriptObjectName, script.ToString(), false); 
            }
        }
 
        base.OnLoad(e);
    }
 
    protected override void Render(HtmlTextWriter writer)
    {
        ValidateBeforeRender(writer);
        base.Render(writer);
    }
 
    /// <summary>
    /// Normalizes the variable names to be used as JavaScript variable names
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    protected static string NormalizeVariableName(string key)
    {
        return key.Replace('.', '_');
    }
}
GlobalResourcesToJavaScript
C#
/// <summary>
/// Represents a class that can be used to render
/// a JavaScript object that contains resource keys and values
/// of a specific global resX file dependant on the CurrentUI culture.
/// </summary>
public class GlobalResourcesToJavaScript : ResourcesToJavaScriptBase
{
    /// <summary>
    /// The name of the Global ResX file (ex: "Resource1"
    ///       if the ResX file is "Resource1.resx")
    /// </summary>
    public string GlobalResXFileName
    {
        get;
        set;
    }
 
    private string _javaScriptObjectName;
    /// <summary>
    /// Sets and Gets the generated JavaScript object name.
    /// if not set it will return the normalized GlobalResXFileName.
    /// </summary>
    public override string JavaScriptObjectName
    {
        set
        {
            _javaScriptObjectName = value;
        }
        get
        {
            if (!string.IsNullOrEmpty(_javaScriptObjectName) && 
                    _javaScriptObjectName.Trim() != string.Empty)
            {
                return NormalizeVariableName(_javaScriptObjectName);
            }
            return NormalizeVariableName(GlobalResXFileName);
        }
    }
 
    protected override string GetResourceValue(string key)
    {
        string value = HttpContext.GetGlobalResourceObject
			(GlobalResXFileName, key) as string;
        return value == null ? string.Empty : value;
    }
 
    protected override string GetResXFilePath()
    {
        return Page.MapPath(Path.Combine("~//App_GlobalResources", 
               GlobalResXFileName + ".resx"));
    }
 
    protected override void ValidateBeforeRender(System.Web.UI.HtmlTextWriter writer)
    {
        if (string.IsNullOrEmpty(GlobalResXFileName) || 
                 GlobalResXFileName.Trim() == string.Empty)
        {
            writer.Write("GlobalResourcesToJavaScript: " + 
              this.ClientID + ": Please specify GlobalResXFileName");
            return;
        }
        base.ValidateBeforeRender(writer);
    }
}

All we need to do is to add an instance of GlobalResourcesToJavaScript to a web page or user control and set the property GlobalResXFileName to the file title of the required resx file.

We also may set the property JavaScriptObjectName to the name we need to call the generated JavaScript object:

XML
<ResourcesToJavaScript:GlobalResourcesToJavaScript 
    ID="GlobalResourceToJavaScript1" runat="server" 
    GlobalResXFileName="Resource1" JavaScriptObjectName="Resources">
</ResourcesToJavaScript:GlobalResourcesToJavaScript>

The generated JavaScript will be something like:

HTML
<script type="text/javascript"> 
  var Resources = { Entry1:'Entry 1 text' , Entry2:'Entry 2 text' , 
                    Entry3:'Entry 3 text' };
</script>

And this can be easily used from any JavaScript code like:

JavaScript
alert(Resources.Entry2);

History

  • 19th February, 2011: Initial post
  • 20th February, 2011: Article updated

License

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


Written By
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
SuggestionAdd a comment Pin
Camilo Martinez [Equiman]6-Nov-14 5:19
Camilo Martinez [Equiman]6-Nov-14 5:19 
BugRe: Add a comment Pin
Camilo Martinez [Equiman]21-Aug-15 8:52
Camilo Martinez [Equiman]21-Aug-15 8:52 
SuggestionHandling single quotes Pin
matthewmarkmiller2-Sep-12 14:11
matthewmarkmiller2-Sep-12 14:11 
GeneralRe: Handling single quotes Pin
Camilo Martinez [Equiman]6-Nov-14 5:21
Camilo Martinez [Equiman]6-Nov-14 5:21 
GeneralGoo job Pin
Sunasara Imdadhusen1-Mar-11 0:27
professionalSunasara Imdadhusen1-Mar-11 0:27 
GeneralRe: Goo job Pin
Adel Refaat1-Mar-11 9:27
Adel Refaat1-Mar-11 9:27 
GeneralMy vote of 5 Pin
Peace ON27-Feb-11 17:32
Peace ON27-Feb-11 17:32 
GeneralRe: My vote of 5 Pin
Adel Refaat27-Feb-11 19:25
Adel Refaat27-Feb-11 19:25 
GeneralMy vote of 5 Pin
justinonday23-Feb-11 20:07
justinonday23-Feb-11 20:07 
Excellent
GeneralRe: My vote of 5 Pin
Adel Refaat25-Feb-11 22:05
Adel Refaat25-Feb-11 22:05 
GeneralExcellent.........!!!!!!!!!!!! Pin
justinonday23-Feb-11 20:07
justinonday23-Feb-11 20:07 
GeneralMy vote of 5 Pin
Monjurul Habib23-Feb-11 17:48
professionalMonjurul Habib23-Feb-11 17:48 
GeneralRe: My vote of 5 Pin
Adel Refaat25-Feb-11 22:06
Adel Refaat25-Feb-11 22:06 
Generalthanks for sharing Pin
Pranay Rana21-Feb-11 2:43
professionalPranay Rana21-Feb-11 2:43 
GeneralMy vote of 5 Pin
Sandeep Mewara20-Feb-11 1:21
mveSandeep Mewara20-Feb-11 1:21 
GeneralRe: My vote of 5 Pin
Adel Refaat20-Feb-11 19:46
Adel Refaat20-Feb-11 19:46 

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.