Converting a generic list into a JSON string and then
handling 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.
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 Listand 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 = "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 theSystem.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">
<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:
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 andRequestFailedCallback.
Here, the ReuqestCompleteCallbackfunction 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);
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;
}
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:
window.onload=GetUserList();
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.
Reference :