How to Format Generic List into JSON string and use it in JavaScript

No.of Views1680
Bookmarked0 times
Downloads 
Votes0
By  jalpesh   On  10 Jan 2011 20:01:20
Tag : JavaScript , Miscellaneous
We all know that JSON (JavaScript Object Notation) is very useful in case of manipulating string on client side with java script and its performance is very good over browsers so let’s create a simple example where convert a Generic List then we will convert this list into JSON string and then we will call this web service from java script and will handle in java script.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

We all know that JSON (JavaScript Object Notification) is very useful in case of manipulating string on client side with java script and its performance is very good over browsers so let’s create a simple example where convert a Generic List then we will convert this list into JSON string and then we will call this web service from java script and will handle in java script.

To do this we need a info class(Type) and for that class we are going to create generic list. Here is code for that I have created simple class with two properties UserId and UserName

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

Now Let’s create a web service and web method will create a class and then we will convert this with in JSON string with JavaScriptSerializer class. Here is web service class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
 
namespace Experiment.WebService
{
   /// /// Summary description for WsApplicationUser
   /// [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 userList = new List();
           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 you must have this attribute here in web service class ‘[System.Web.Script.Services.ScriptService]’ as this attribute will enable web service to call from client side.
Now we have created a web service class let’s create a java script function ‘GetUserList’ which will call web service from JavaScript like following

function GetUserList() {
   Experiment.WebService.WsApplicationUser.GetUserList(ReuqestCompleteCallback, RequestFailedCallback);
  
}

After as you can see we have inserted two call back function ReuqestCompleteCallback and RequestFailedCallback which handle errors and result from web service. ReuqestCompleteCallback will handle result of web service and if and error comes then RequestFailedCallback will print the error. Following is code for both function.

function ReuqestCompleteCallback(result) {
           
           result = eval(result);
           var divResult = document.getElementById("divUserList");
           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 + "
" +
                             "Service Error: " + message + "
" +
                             "Status Code: " + statusCode + "
" +
                             "Exception Type: " + exceptionType + "
" +
                             "Timedout: " + timedout;
       }

Here in above there is a function called you can see that we have use ‘eval’ function which parse string in enumerable form. Then we are calling a function call ‘CreateUserListTable’ which will create a table string and paste string in the a div. Here is code for that function.

function CreateUserListTable(userList) {
 
           var tablestring = '';
           
           for (var i = 0, len = userList.length; i < len; ++i)
           {
               tablestring=tablestring + "";
               tablestring=tablestring + "";
               tablestring=tablestring + "";
               tablestring=tablestring + "";
           }
           tablestring = tablestring + "
UsreIDUserName
" + userList[i].UserId + "" + userList[i].UserName + "
"; var divResult = document.getElementById("divUserList"); divResult.innerHTML = tablestring; }

Now let’s create div which will have all html that is generated from this function. Here is code of my web page. We also need to add a script reference to enable web service from client side. Here is all HTML code we have.

Now as we have not defined where we are going to call ‘GetUserList’ function so let’s call this function on windows onload event of javascript like following.

window.onload=GetUserList();

That’s it. Now let’s run it on browser to see whether it’s work or not and here is the output in browser as expected. 

Image Loading

That’s it. This was very basic example but you can crate your own JavaScript enabled grid from this and you can see possibilities are unlimited here. Stay tuned for more. Happy programming..

 
Sign Up to vote for this article
 
About Author
 
jalpesh
Occupation-Software Engineer
Company-DotNetJaps
Member Type-Gold
Location-India
Joined date-08 May 2010
Home Page-http://www.dotnetjalps.com
Blog Page-http://www.dotnetjalps.com
I am jalpesh vadgamaa an Microsoft MVP for Visual C# and BrainBench Certified ASP.NET Developer having experience of five year in Microsoft .NET Technology.I am working as Project Leader in Mid Size company.My work area comprises of Enterprise Level projects using ASP.NET and other Microsoft .NET Technologies.Please feel free to contact me for any queries via posting comments on my blog I will try to reply as early as possible.
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top