Quantcast
Viewing all articles
Browse latest Browse all 41

Creating and Calling ASP.NET AJAX Web Service

Hi,

First we will create a new ASP.NET Ajax web site(Visual Studio 2005)
or ASP.NET web site (version 3.5) if we are using Orcas(Visual studio 2008)

Through Add New Item, add a new web service WebService.asmx in the website.

1) Add this in webservice.cs

using System.Web.Script.Services;


2) Add a ScriptService attribute to our webservice class

[ScriptService]
[WebService(Namespace = “http://tempuri.org/”)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

3) We’ll use the default Hello World web service. So just save the web service and view it in browser to test it.

Now change the url of the webservice in browser and append “/js” to it
i.e.
Change
http://d-0824/AjaxinAction/WebService.asmx
to
http://d-0824/AjaxinAction/WebService.asmx/js

Press enter it will ask you to save the file,
just save and open it in notepad

We will see something like this

var WebService=function() {
WebService.initializeBase(this);
this._timeout = 0;
this._userContext = null;
this._succeeded = null;
this._failed = null;
}
WebService.prototype={
_get_path:function() {
…………………………
……………………….

This is a javascript proxy class which the our client side ajax library will use to make call to our web service.

4) Add a script manager control to our default.aspx page ( if not already there), and add the reference to our web service

<asp:ScriptManager ID=”ScriptManager1″ runat=”server”>
<Services>
<asp:ServiceReference Path=”WebService.asmx” />
</Services>
</asp:ScriptManager>

5) Now add a simple html text control on the default.aspx page. We will be calling our web service and fill the text box value returned from the webservce (“Hello World”).

<input id=”Text1″ type=”text” />

6) Put this script on your default.aspx page

<script type=”text/javascript”>

function pageLoad()
{
WebService.HelloWorld(onSuccess);
}

function onSuccess(result)
{
$get(“Text1”).value=result;
}

</script>

7) Now just view the page in browser we should see the textbox filled with “Hello World” string returned from our web service.

8) Or if we want to call it in the click of the button. add a html button control.

<input id=”Button1″ type=”button” value=”button” />

9) Replace the above script with this one

<script type=”text/javascript”>
var myButton=null;
function pageLoad(sender,e)
{
myButton=$get(“Button1″);
$addHandler(myButton,”click”,btn_click);
}

function btn_click(sender,e)
{
WebService.HelloWorld(onSuccess);
}

function onSuccess(result)
{
$get(“Text1”).value=result;
}
</script>

In the above example we saw a client centric approach, the same thing can be done very easily by making use  of server centric approach in ASP.NET AJAX framework.

https://nishantrana.wordpress.com/2007/11/06/creating-a-simple-hello-world-aspnet-ajax-web-page/

Bye

 


Viewing all articles
Browse latest Browse all 41

Trending Articles