Click here to Skip to main content
15,867,308 members
Articles / Web Development / ASP.NET

Javascript Dictionary

Rate me:
Please Sign up or sign in to vote.
4.87/5 (19 votes)
27 Apr 2012CPOL2 min read 153K   33   18
Javascript Dictionary

I don't know, may be some of you already know this... But I recently, worked on JavaScript dictionary. And that was really interesting. So I wanted to share my findings with you all. Please share your feedback about my post.

JavaScript provides us a way to make a Dictionary object and use it same like a C# dictionary. Although we would not be having all the properties that are supported by C# dictionary, we will be able to use it as dictionary, i.e. in key value format.

Let’s see one simple example:

I have stored a list of all weekdays as keys and assigned some numbers to these as values. Let’s see the code.

JavaScript
function CreateDayDictionary() {
var days = new Array();
days['Sunday'] = 1;
days['Monday'] = 2;
days['Tuesday'] = 3;
days['Wednesday'] = 4;
days['Thursday'] = 5;
days['Friday'] = 6;
days['Saturday'] = 7;
}

Now to fetch it any point of time… we can fetch it like this. Here, I have made a function to alert some data. It can be as:

JavaScript
function ShowDays() {
       alert(days['Sunday']);
       alert(days['Thursday']);
       alert(days['Saturday']);
   }

It will show three alerts. First 1 then 5 and at last 7.

So, we can store some global data in our page. And this data we can access, at different events we require.

Similarly, we can store objects in the dictionary in the same way. Let’s see the code:

JavaScript
function CreateDictionarywithObject() {
       var objDictionary = new Array();
       // Creating a dictionary which is holding five objects
       for (var i = 0; i < 5; i++) {

           var obj= new myClass();
           obj.member1 = 'member1data' + i;
           obj.member2 = 'member2data' + i;
           obj.member3 = 'member3data' + i;

           objDictionary['Obj' + i] = obj;
       }
       //Fetching third Object
       var fetchedObj = objDictionary['Obj3'];
       alert(fetchedObj.member1);
       alert(fetchedObj.member2);
       alert(fetchedObj.member3);
   }

Now, one more thing if you want to pass the data from server to client as JSon data, you can serialize a C# dictionary at server side, and again when you will desteralize at client side, you will be getting the dictionary as we discussed above. Let’s see the magic.

Here I have made one class Employee as:

C#
public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Salary { get; set; }
    public int Age { get; set; }
}

Now, on page load, I created a dictionary with some data, like below:

C#
List<Employee> employees= new List<Employee>()
        {
            new Employee{ Id=1000, Name="Brij", Age=27, Salary=800000},
            new Employee {Id=1001, Name = "Rahul", Age=28,Salary=500000},
            new Employee {Id=1002, Name = "Anoop", Age= 29 ,Salary = 60000}
        };
Dictionary<string, Employee> employeeData = employees.ToDictionary
				(em => em.Id.ToString(), emp => emp);

Now serialize data using JavaScriptSerializer and assign in a hidden variable:

C#
JavaScriptSerializer ser = new JavaScriptSerializer();

hfData.Value = ser.Serialize(employeeData);

Now I have a textbox and a button to show employee details. My aspx code looks like this:

XML
<div>
        <span>Id: </span>  <input id="idName" />

        <input id="Button2" onclick="show();" type="button" value="Displaydetail" />
        <hiddenfield id="hfData" runat="server" />
    </div>

Here, I will be entering the Id of the employee, and on clicking the button “Show details”, I am displaying the data as a JavaScript alert. So let’s see the JavaScript code:

JavaScript
function parseEmployeeData() {
        //for parsing the data
        employees = JSON.parse(document.getElementById("<%= hfData.ClientID%>").value);
    }

    function show() {
        parseEmployeeData();
        var key = document.getElementById('idName').value;
        var emp = employees[key];
        if (typeof (emp) != 'undefined') {
        // If key is found then display the details
            alert(emp.Name);
            alert(emp.Age);
            alert(emp.Salary);
        }
        else {
        // key not found
            alert('No data found');
        }
    }

As you can see, first I am parsing the data using json, then finding the key in the dictionary and displaying the details as a JavaScript alert.

This sample is just for an example, to show how we can use JavaScript dictionary in our daily lives.

Here, I have used namespace System.Web.Script.Serialization for serializing the data in C#. Also included is the JSON JavaScript file to parse the data.

Happy client scripting!

Thanks,

Brij


License

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


Written By
Software Developer (Senior)
India India
Brij is a 3-times Microsoft MVP in ASP.NET/IIS Category and a passionate .NET developer. More than 6 years of experience in IT field, currently serving a MNC as a Tech Lead/Architect.

He is a very passionate .NET developer and have expertise over Web technologies like ASP.NET 2.0/3.5/4.0, jQuery, JSON, Javascript, IIS and related technologies. He is also a Exchange Server (EWS) Specialist. He has great experience in design patterns and N-Tier Architecture.

He is also certified as Microsoft Certified Technologies Specialist-ASP.NET and Microsoft Certified Technologies Specialist-WCF in .NET 4.0. He has also received several awards at various forums and his various articles got listed as "Article of the day" at ASP.NET Microsoft Official Website www.asp.net.

He has done MCA from NIT Durgapur and completed his graduation from Lucknow University.

Learning new technologies and sharing knowledge excites him most. Blogging, solving problems at various forums, helping people, keeps him busy entire day.


Visit his Blog: Code Wala

Area of Expertise :
C#, ASP.NET 2.0,3.5,4.0, AJAX, JQuery, JSON, XML, XSLT, ADO.Net, WCF, Active Directory, Exchange Server 2007 (EWS), Java script, Web Services ,Win services, DotnetNuke, WSS 3.0,Sharepoint Designer, SQL Server 2000/2005/2008

Comments and Discussions

 
QuestionThanks! Pin
Hugo Lesiuk11-Nov-14 8:24
Hugo Lesiuk11-Nov-14 8:24 
Thanks my friend, u helped me a lot!
GeneralMy vote of 5 Pin
member6027-Apr-12 22:38
member6027-Apr-12 22:38 
Generalrender a dic with JSON is so cool! Pin
ericpxz27-Apr-12 7:12
ericpxz27-Apr-12 7:12 
SuggestionPlease remove the span tags Pin
Patrick-Wayfarer26-Apr-12 16:59
professionalPatrick-Wayfarer26-Apr-12 16:59 
GeneralRe: Please remove the span tags Pin
Brij27-Apr-12 3:37
mentorBrij27-Apr-12 3:37 
GeneralMy vote of 5 Pin
Deb-Samrat12-Jul-11 10:17
Deb-Samrat12-Jul-11 10:17 
GeneralRe: My vote of 5 Pin
Brij12-Jul-11 21:23
mentorBrij12-Jul-11 21:23 
Question???? Pin
NavnathKale8-Nov-10 6:25
NavnathKale8-Nov-10 6:25 
AnswerRe: ???? Pin
Brij8-Nov-10 7:01
mentorBrij8-Nov-10 7:01 
GeneralMy vote of 5 Pin
hahanottelling18-Oct-10 14:42
hahanottelling18-Oct-10 14:42 
GeneralRe: My vote of 5 Pin
Brij18-Oct-10 17:25
mentorBrij18-Oct-10 17:25 
GeneralMy vote of 5 Pin
Hiren solanki13-Oct-10 3:24
Hiren solanki13-Oct-10 3:24 
GeneralRe: My vote of 5 Pin
Brij13-Oct-10 4:56
mentorBrij13-Oct-10 4:56 
GeneralMy vote of 2 Pin
buyong10-Oct-10 20:01
buyong10-Oct-10 20:01 
GeneralRe: My vote of 2 Pin
Brij11-Oct-10 6:27
mentorBrij11-Oct-10 6:27 
GeneralRe: My vote of 2 Pin
Hiren solanki13-Oct-10 3:15
Hiren solanki13-Oct-10 3:15 
GeneralRe: My vote of 2 Pin
Brij13-Oct-10 4:56
mentorBrij13-Oct-10 4:56 
GeneralRe: My vote of 2 Pin
Abhijit Jana11-Oct-10 7:38
professionalAbhijit Jana11-Oct-10 7:38 

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.