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

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

Rate me:
Please Sign up or sign in to vote.
4.56/5 (11 votes)
11 Jan 2011CPOL3 min read 151.8K   1.2K   20   12
How to convert a generic list into a JSON string and then handle it in JavaScript.

Introduction

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.

Background

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:

C#
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:

C#
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 = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script,
    // using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class WsApplicationUser : System.Web.Services.WebService
    {

        [WebMethod]
        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());
                userList.Add(userInfo);

            }
            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:

HTML
<form id="form1" runat="server">
<asp:ScriptManager ID="myScirptManger" runat="Server">
    <Services>
        <asp:ServiceReference 
           Path="~/WebService/WsApplicationUser.asmx" />
    </Services>
</asp:ScriptManager>

<div id="divUserList">
</div>
</form>

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:

JavaScript
function GetUserList()
{
    Experiment.WebService.WsApplicationUser.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:

JavaScript
function ReuqestCompleteCallback(result)
{
    result = eval(result);
    CreateUserListTable(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" + 
        "</td><td>UserName</td></tr>';

    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:

JavaScript
window.onload=GetUserList();

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

Image 1

Conclusion

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.

License

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


Written By
DotNetJalps
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:///www.twitter.com/jalpesh. 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 http://www.dotnetjalps.com as well I am active members few communities likes weblogs.asp.net,beyondrelational.com etc.

Comments and Discussions

 
QuestionList<string> Pin
Farnaz_Farnaz26-Apr-13 5:54
Farnaz_Farnaz26-Apr-13 5:54 
GeneralExcellent article Pin
S V Saichandra8-Apr-12 8:45
professionalS V Saichandra8-Apr-12 8:45 
Generalnice Pin
Pranay Rana12-Jan-11 9:14
professionalPranay Rana12-Jan-11 9:14 
GeneralOne thing About JSON Pin
ZeroDev10-Jan-11 7:10
ZeroDev10-Jan-11 7:10 
GeneralRe: One thing About JSON Pin
Jalpesh Vadgama11-Jan-11 1:20
Jalpesh Vadgama11-Jan-11 1:20 
General[My vote of 1] hmmm Pin
Selvin10-Jan-11 2:14
Selvin10-Jan-11 2:14 
GeneralRe: [My vote of 1] hmmm Pin
Jalpesh Vadgama10-Jan-11 5:11
Jalpesh Vadgama10-Jan-11 5:11 
GeneralRe: [My vote of 1] hmmm Pin
Selvin11-Jan-11 3:49
Selvin11-Jan-11 3:49 
GeneralThanks, But some error. Pin
olge9-Jan-11 22:19
olge9-Jan-11 22:19 
GeneralRe: Thanks, But some error. Pin
Jalpesh Vadgama9-Jan-11 22:27
Jalpesh Vadgama9-Jan-11 22:27 
GeneralRe: Thanks, But some error. Pin
Jalpesh Vadgama9-Jan-11 22:30
Jalpesh Vadgama9-Jan-11 22:30 
Hello,

See following link it's a internet explorer settings.

http://support.microsoft.com/kb/811262[^]

Best Regards,
Jalpesh
Software Developer

GeneralMy vote of 4 Pin
kirti.darji9-Jan-11 21:12
kirti.darji9-Jan-11 21:12 

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.