Click here to Skip to main content
13,247,848 members (61,766 online)
Click here to Skip to main content
Add your own
alternative version


20 bookmarked
Posted 9 Jan 2011

Converting a generic list into a JSON string and then handling it in JavaScript

, 11 Jan 2011
Rate this:
Please Sign up or sign in to vote.
How to convert a generic list into a JSON string and then handle it in JavaScript.


We all know that JSON (JavaScript Object Notation) is very useful for manipulating strings on client side with JavaScript, and its performance is very good over various browsers. In this article, I will describe how we can easily convert a C# Generic list into a JSON string with the help of the JavaScript Serializer class, and how we can get this string into JavaScript using the ASP.NET ScriptManager by calling a Web Service with JavaScript. I manipulate the string in JavaScript to generate custom HTML.


I will develop a simple ASP.NET web application which contains the Web Service, and the web page which will contain the JavaScript code to produce custom HTML at the client side with JSON.

Let's Get Started

To create a Generic List of a custom type, we need an Info class which contains some properties. I have created the class UserInfo which contains the properties called UserId and UserName. Shown below is the code for that:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Experiment
    public class UserInfo
        public int UserId { get; set; }
        public string UserName { get; set; }

Like we have done with the class, let's create a Web Service which will create a Generic List of the above class, and then we will create some data for the List using a for loop. After creating a Generic List with data, we will use the JavaScriptSerializer class to serialize the List and convert it into a JSON string. Here is the code for that:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace Experiment.WebService
    /// <summary>
    /// Summary description for WsApplicationUser
    /// </summary>
    [WebService(Namespace = "")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    // To allow this Web Service to be called from script,
    // using ASP.NET AJAX, uncomment the following line. 
    public class WsApplicationUser : System.Web.Services.WebService

        public string GetUserList()
            List<UserInfo> userList = new List<UserInfo>();
            for (int i = 1; i <= 5; i++)
                UserInfo userInfo = new UserInfo();
                userInfo.UserId = i;
                userInfo.UserName = 
                  string.Format("{0}{1}", "J", i.ToString());

            System.Web.Script.Serialization.JavaScriptSerializer jSearializer = 
                   new System.Web.Script.Serialization.JavaScriptSerializer();
            return jSearializer.Serialize(userList);

Note: Here, we must have the System.Web.Script.Services.ScriptService attribute call the Web Service from JavaScript.

Now, as we have done with the Web Service, let's create the HTML part to consume the custom HTML generated by the JavaScript. First of all, we need to add a service reference to the Web Service which we need to use on the client side through JavaScript. And we will also create a div 'divUserList' which will contain the custom HTML generated via JavaScript. So our HTML code in the WebForm will look like this:

<form id="form1" runat="server">
<asp:ScriptManager ID="myScirptManger" runat="Server">

           Path="~/WebService/WsApplicationUser.asmx" />

<div id="divUserList">

Now that we have created a Web Service class, let's create a JavaScript function 'GetUserList' which will call the Web Service from the JavaScript, like shown:

function GetUserList()
                ReuqestCompleteCallback, RequestFailedCallback);

As you can see, in the above code, I have implemented two callback functions in JavaScript: ReuqestCompleteCallback and RequestFailedCallback. Here, the ReuqestCompleteCallback function will contain code for converting a JSON string into custom HTML, and the RequestFailedCallback function will contain code for handling the Web Service and other errors if any errors occur. Shown below is the code:

function ReuqestCompleteCallback(result)
    result = eval(result);

function RequestFailedCallback(error)
    var stackTrace = error.get_stackTrace();
    var message = error.get_message();
    var statusCode = error.get_statusCode();
    var exceptionType = error.get_exceptionType();
    var timedout = error.get_timedOut();

    // Display the error.
    var divResult = document.getElementById("divUserList");
    divResult.innerHTML = "Stack Trace: " + stackTrace + "<br/>" +
        "Service Error: " + message + "<br/>" +
        "Status Code: " + statusCode + "<br/>" +
        "Exception Type: " + exceptionType + "<br/>" +
        "Timedout: " + timedout;

function CreateUserListTable(userList)
    var tablestring = '<table ><tr><td>UsreID" + 

    for (var i = 0, len = userList.length; i < len; ++i) 
        tablestring=tablestring + "<tr>";
        tablestring=tablestring + "<td>" + 
                    userList[i].UserId + "</td>";
        tablestring=tablestring + "<td>" + 
                    userList[i].UserName + "</td>";
        tablestring=tablestring + "</tr>";
    tablestring = tablestring + "</table>";
    var divResult = document.getElementById("divUserList");
    divResult.innerHTML = tablestring;

How the above code works

As you can see, in the above code, ReuqestCompleteCallback will parse a string with the JavaScript EVal function which will convert the JSON string into enumerable form. After that, it will pass that result variable to another function called CreateUserListTable, which create an HTML table string by iterating with a for loop. Then it will put that table string in the inner HTML of the container div.

The same way, if any error occurs, RequestFailedCallback will handle the Web Service error and will print all the error information in the div's inner HTML.

Now we need to call the GetUserList function on the page. We have to add JavaScript code like shown below:


That's it. Let's run this application, and below is the output as expected. It's easy.


As you can see, it's very easy to convert a C# generic list into custom HTML with help of JSON. This was a very basic example. You can extend this example and can create a JavaScript client side grid with paging and sorting and other features. The possibilities are unlimited. Hope your liked my effort.


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


About the Author

Jalpesh Vadgama
India India
I am Jalpesh Vadgama a former Microsoft MVP for Visual C# and BrainBench Certified ASP.NET Developer having more then 10 years of experience in .NET Technology.

Before that I had completed My B.Sc(Chemistry) and Masters of Computer Application from Saurashtra University. I started my career working on windows application with Microsoft.NET framework 1.1 and then I moved to ASP.NET and still exploring ASP.NET 4.0. Right now I am working as Project Leader in midsized company.

You are free use to any code in your project. But please don't copy this content directly on blog or site as I am putting an extra effort for that.

Please feel free to contact me for any queries via posting comments on my blog I will try to reply as early as possible. You can also contact me on twitter at http:/// I am not tweeting too much but will surely get back to you if you are going to contact me.

I also write blogs at as well I am active members few communities likes, etc.

You may also be interested in...


Comments and Discussions

QuestionList<string> Pin
Farnaz_Farnaz26-Apr-13 6:54
memberFarnaz_Farnaz26-Apr-13 6:54 
GeneralExcellent article Pin
S V Saichandra8-Apr-12 9:45
memberS V Saichandra8-Apr-12 9:45 
Generalnice Pin
Pranay Rana12-Jan-11 10:14
memberPranay Rana12-Jan-11 10:14 
GeneralOne thing About JSON Pin
ZeroDev10-Jan-11 8:10
memberZeroDev10-Jan-11 8:10 
GeneralRe: One thing About JSON Pin
Jalpesh Vadgama11-Jan-11 2:20
memberJalpesh Vadgama11-Jan-11 2:20 
General[My vote of 1] hmmm Pin
Selvin10-Jan-11 3:14
memberSelvin10-Jan-11 3:14 
GeneralRe: [My vote of 1] hmmm Pin
Jalpesh Vadgama10-Jan-11 6:11
memberJalpesh Vadgama10-Jan-11 6:11 
GeneralRe: [My vote of 1] hmmm Pin
Selvin11-Jan-11 4:49
memberSelvin11-Jan-11 4:49 
GeneralThanks, But some error. Pin
olge9-Jan-11 23:19
memberolge9-Jan-11 23:19 
GeneralRe: Thanks, But some error. Pin
Jalpesh Vadgama9-Jan-11 23:27
memberJalpesh Vadgama9-Jan-11 23:27 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.171114.1 | Last Updated 11 Jan 2011
Article Copyright 2011 by Jalpesh Vadgama
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid