Click here to Skip to main content
6,295,667 members and growing! (12,429 online)
Email Password   helpLost your password?
Web Development » Web Services » General     Beginner License: The Code Project Open License (CPOL)

Calling Web Service from HTML page using AJAX. Sample Web Service application

By Amit Kumar Thakur

Calling Web Service from HTML page using AJAX. Sample Web Service application
C# (C# 2.0), Javascript, XML, HTML, .NET (.NET 2.0), ASP.NET, Ajax, Dev, Design
Posted:22 Jul 2008
Updated:24 Aug 2008
Views:10,652
Bookmarked:18 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
7 votes for this article.
Popularity: 2.27 Rating: 2.69 out of 5
1 vote, 14.3%
1
2 votes, 28.6%
2
2 votes, 28.6%
3
2 votes, 28.6%
4

5

Introduction

This is a sample application which makes AJAX calls to web service. This article discusses the server side aspect of the application.

The web service performs the task of fetching and storing the data from SQL server database at server. This article explains the server side aspect of the application. For discussion about how the UI layer works at client end please read: Calling A Web Service From HTML Page.....(for all browsers)

Using the Code

The model used is as the image shown below:
model.gif

The Client side UI layer is discussed in article Calling A Web Service From HTML Page..(for all browsers).

The Application Logic layer has two layers: Business Object Layer(BL) and data access layer(DAL). DAL contains the class PollService. PollService is made a web service class by exposing some of its methods as WebMethods.

There are two more details which are optional - 1. Inheriting your web service class from WebService class of System.Web.Services namespace. 2. Applying WebService attribute to the class declaration. This will give us give us an advantage of having access to built-in Asp.Net objects Application,Context,Server,Session,User. If we don't need to use these objects, we can skip these details.

Here, PollService class exposes the methods: AddPoll ,CastMyVote ,CastVoteByPollId ,GetAllPollResults ,GetLatestPoll , GetListOfPolls ,GetPollById ,GetPollResultById as web methods to web services interface. This is done by decorating their method declarations with [WebMethod()] attribute.

Further important step is to specify the xml-namespace. Xml-namespace identifies your web service over the internet. When no xml-namespace is provided for the class, .Net provides a default namespace http://tempuri.org/ which is suitable for testing purpose only to. We give our webservice a namespace with the following declaration:

[WebService(Namespace="http://mydummydomain.com/webservices/",
                Description="This is demo polling Web Service.")]
public class PollService : System.Web.Services.WebService
    {

(Please make sure to be comfortable with creation of web services beforehand as this is a demo project only and this article should not be considered as a complete tutorial for web services at all. This article by Chris Maunder would be a very good start.)

The web methods of our web-service class look somewhat like this:

namespace pollLogicalLayer.LogicalLayer.DAL
{
    public class PollService : System.Web.Services.WebService
    {
......
       [WebMethod()]
       public List GetListOfPolls()
       {
//code to access database, fill the list of PollServiceBO objects and return this list.
//PollServiceBO is discussed below.
       }
       [WebMethod()]
       public PollServiceBO GetLatestPoll()
    {
//............
    }
        [WebMethod()]
        public string CastVoteByPollId(string UserId,int PollId,Int16 SelectedOption)
        {
.............
        }
        [WebMethod()]
        public PollServiceBO GetPollResultById(int PollId)
        {
.............
        }
        [WebMethod()]
        public List GetAllPollResults()
        {
................
        }
        [WebMethod()]
        public PollServiceBO GetPollById(int PollId)
        {
..............
        }
        [WebMethod()]
        public int AddPoll(string Question,string option1,string option2,string option3,string option4)
        {
.................
        }
        [WebMethod()]
        public string CastMyVote(string UserId, Int16 SelectedOption)
        {
...............
        }

    }
}
  

Above methods take simple parameters as arguments like int,string,DateTime etc. as these are serializable data-types. The information is returned in form of objects of the class PollServiceBO. The business object PollServiceBO is kept in the namespace pollLogicalLayer.LogicalLayer.BL. Generally Web service business objects are kept separate from actual business objects. Web service objects should then instantiate business objects for actual data access operations. The code for PollServiceBO class is self explanatory:

    public class PollServiceBO 
    {
        private int _id;
        private string _question;
        private string _option1;
        private string _option2;
        private string _option3;
        private string _option4;
        private DateTime _dateAdded;
        //the getters and setters for the above fields
        }

The default database used for Database Layer is the SQL Server file poll.mdf kept in App_Data folder of the application. This layer contains simple stored procedures with the same names(AddPoll ,CastMyVote ,CastVoteByPollId....) as above for fetching/inserting data. The SQL script for the database(pollDb.sql) could be downloaded from above. If poll Database is to be changed to alternate Server, the connection String should be changed accordingly. Please make sure to place some data in poll database before making request to fetch. When server is changed, the connectionstring can be changed like this:

<connectionStrings>
<add name="pollConnectionString" connectionString="Data Source={Target Server Name};
Initial Catalog=poll;Integrated Security=SSPI;Connect Timeout=10"
providerName="System.Data.OleDb" />
</connectionStrings>

If the application is set up, PollService.asmx can be viewed in browser like this:
pollservice.gif
All the methods exposed by the web service are visible as in the image above. Please make sure to test the web service by invoking a web method, before using the UI. e.g.- click on GetLatestPoll and press invoke button. If xml response is visible then UI layer will be able to fetch the data.

If there is no response when web method is invoked, please browse Default.aspx which checks the objects directly. General cause for this is improper access to the database file.

If XML response is visible but UI is not able to fetch the data, please correct the location of the web service.
For Example- In CastMyVote UI, we have location of WebService as

var url = "http://localhost/poll/PollService.asmx/CastMyVote";
This says that PollService.asmx is hosted in poll folder on localhost ie. it is in c:\inetput\wwwroot\poll directory. If we want to host it from Visual Studio's inbuilt web server or any other server, the location is needed to be changed in all pages.E.g.-
"http://localhost:2080/poll/PollService.asmx/CastMyVote"
//above one is location when my inbuilt web server hosts my website on port 2080
"http://www.my_domain.com/poll/PollService.asmx/CastMyVote"
//this would be location if we host the PollService.asmx from a folder named poll in website www.my_domain.com

Index.htm is the start Page. Some of the pages are based upon the webservice.htc approach which works for Internet Explorer only.

Note:

Please note that this application exposes the functions of data access layer directly to the UI for demonstration purpose only. Web service business objects are kept different from application business objects. This is because to expose any field of the object returned by a web service, we will have to keep it as public read/write field. This is needed to keep this object serializable. We would never like to expose all the fields of our business objects and the methods of Data Access Layer directly. Hence a more legible approach will have:

public class PollServiceBO
{
        public PollServiceBO(PollBO b)
        {
            this._id = b.ID;
            this._question = b.question;
            this._option1 = b.option1;
            this._option2 = b.option2;
            this._option3 = b.option3;
            this._option4 = b.option4;
            this._dateAdded = b.dateAdded;
        }
/***** the usual getters and setters ****/

}

And the web service class should use the Data Access Layer and application business objects to interact with application (after validation).

[WebService(Namespace="http://mydummydomain.com/webservices/",
                Description="This is demo polling Web Service.")]
public class PollService : System.Web.Services.WebService
    {

[WebMethod(CacheDuration = 30,Description="Returns list of latest 100 polls.")]
       public List<pollserviceBO> GetListOfPolls()
       {
List<pollserviceBO> polls = PollDAL.GetListOfPolls();
List<pollserviceBO> returnpolls = new List<pollserviceBO>();
foreach (PollBO b in polls)
{
                   PollServiceBO pl = new PollServiceBO(b);
                   returnpolls.Add(pl);
}
return returnpolls;
}
....
}

Authentication,abstraction of the DAL from UI Layer and state-management(if required) is a matter of further important consideration.

Further, I have enabled HTTP GET & POST interaction for this application by modifying Web.config file. I am processing the returned XML response using the UI javascript. However, if we do not want to do this and wish to enable session and authentication-authorization for this application, there is a workaround. We will need to create proxy classes using wsdl.exe or using Visual Studio using Web Reference approach. We write aspx pages which consume our web service using the proxy classes created above. These aspx pages collect simple parameters and return xml response from and to our ajax enabled UI interface.

Proxy class makes our life very simple as it takes care of generating the correct SOAP message and sending it over HTTP. It also takes care of converting the response message to corresponding .Net data types.

For information regarding how UI layer works, please see the article: Calling A Web Service From HTML Page.....(for all browsers)

Links

License

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

About the Author

Amit Kumar Thakur


Member
"go back and revise the stuff from where you copied this.... Your employer would probably not be happy to see you publishing such a poor reflection on the quality of his employees......actually.... you should be Embarrassed...."

Amit Kumar Thakur wrote:
however I request further comments please. -
How about this: Based on your response to the two comments already made, I have no intention of wasting any time commenting on this half-baked, badly written first draft..

KICKING HARDER THAN EVER BEFORE.....
STILL.... THIS IS NOT THE LAST BATTLE AND STILL.... THIS IS NOT THE BEST FIGHT WHICH I CAN PUT UP.
Occupation: Web Developer
Location: India India

Other popular Web Services articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 2 of 2 (Total in Forum: 2) (Refresh)FirstPrevNext
GeneralHi,There is some bug!! PinmemberJLKEngine00820:08 16 Sep '08  
GeneralRe: Hi,There is some bug!! PinmemberAmit Kumar Thakur17:58 11 May '09  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 24 Aug 2008
Editor:
Copyright 2008 by Amit Kumar Thakur
Everything else Copyright © CodeProject, 1999-2009
Web20 | Advertise on the Code Project