Tuesday, September 21, 2010

Binding data on page using Ajax calls (Jquery + Json)- The web-service


Few days back i got a requirement to create a page that has around 200 controls and each control's value refreshes when i click on any one of it. I first tried it using server side code but it was taking too much load and i find it difficult to do it in that way.

I am not familier with javascript programming. but i decided to make it using Jquery & Json.What i know about both is as follow:

1. jQuery: The Write Less, Do More, JavaScript Library

2. JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate.

It takes a lot of time for me to do it in this way. but it make me confident that i am writing this blog and sharing my experience.

Lets see what you think about it :-) , Please post your comments.


This application contains below three parts:

1.Web Service
2.Javascript File
3.Web Page

Here we are creating the first part - The Web-Service

Web Service: It can be a Normal Asp.net web-service or WCF web service, you can select between it according to your requirement. I was not so familier with WCF thats why I selected a simple web service for my project.

Add Namespaces first in asmx class:
1. using System.Web.Script.Services;
2. using System.Web.Script.Serialization;


Why do we need these namespaces?
Well lets start with System.Web.Script.Services namespace. We are using it for adding response formats to the methods ie:- json. It contains Enum for it and contains two values in it ie:- Json & xml. So we get Json return type from this namespace.

Now System.Web.Script.Serialization, It contains classes that provide Javascript Object Notation (JSON) serialization and deserialization for managed type.we are using serialize method of JavaScriptSerializer class. So we get the method to serialize our object from System.Web.Script.Serialization namespace.


How is my webservice going to respond to the ajax calls?
To enable webservice to respond to ajax call uncomment below “[System.Web.Script.Services.ScriptService]” written on the top of the webservice class.

Method: Below is example to web method that return Json format, create a method using these syntax with json return type:














Don't worry about the properties in method , they are just for my game.

So lets discuss this method. As you can see return type is on the top of the method
“[ScriptMethod(ResponseFormat = ResponseFormat.Json)]”. At the end of the method you can see that we are using a List collection and converting it into Json formated string using serialize method of JavaScriptSerializer class.

So here my web service is ready for Ajax calls. Check out my next post for Application part.

Cheers,
Vikas Sharma

No comments:

Post a Comment