Ajax-enabled Web Services with ScriptManager
Clique aqui para ver este post em Português
In this post I'll show an incredible ASP.Net feature I've learned recently: Ajax-enabled Web Services.
With the ScriptManager component (that we've already seen in this post) we're able to consume a Web Service in our Web Site and use the results in JavaScript with little to none specific programming effort. With this component, the Web Service looks like it's a client script object.
Let's start with a new Web Site in Visual Studio (the Visual Web Developer express edition works fine, too). Choose a folder to save the Web Site (you don't need the IIS installed in order to test de project). Now we'll create the Web Service.
Right-click the Web Site's root directory and choose Add New Item. In the dialog box select Web Service. Name it AjaxWs.asmx and click Ok. The IDE should open the file App_Code/AjaxWs.cs. This is where we're gonna work.
Let's leave its implementation as it is for now. It should come with a sample method HelloWorld. The only thing we'll do is "enable" the client script calls. To do that find the class definition:public class AjaxWs : System.Web.Services.WebService
In the line above there's a commented class decoration that we only need to remove the comment bars to enable this feature:// [System.Web.Script.Services.ScriptService]
So, remove the comment and save the file and click the menu Build > Build Web Site.
The Web Service part is done (for now). Now we're gonna code the Web Form that calls the Web Service. Open the Default.aspx file and go to the visualization "Source" or "Split". Below the form tag<form id="form1" runat="server">
We're gonna add a ScriptManager component. You can drag it from the toolbox or simply type manually the asp:ScriptManager tag. The VS makes the effort of type the tags manually very smooth, even if it may not seem that way. After done the tag looks like this:<asp:ScriptManager runat="server" ID="ScriptMngr">
<Services>
<asp:ServiceReference Path="~/AjaxWs.asmx" />
</Services>
</asp:ScriptManager>
We'll now create a client script block in our Web Form. Find the head section and add a script block inside. Here's the code:<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript">
function executarWs() {
AjaxWs.HelloWorld(
function(resultado) {
alert(resultado)
}
)
}
</script>
</head>
I'll give a brief explanation about this script:
AjaxWs - Our Web Service - was created by VS when we added the ScriptManager component and referenced the ~/AjaxWs.asmx Web Service. We're coding a method call to Hello World and pass a function as an argument - more precisely a callback. A callback is a function definition that is called when the function that took is as an argument needs. Think of it as some sort of event handler. But it's subject for another post.
Now we need to call this method. We've seen "new feature" part. Now we're gonna call our Web Service's methods as an ordinary JavaScript call. We'll create a HTML button to call the JavaScript function:<button onclick="executarWs()">Clique aqui</button>
Here goes the complete WebForm's code:<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript">
function executarWs() {
AjaxWs.HelloWorld(
function(resultado) {
alert(resultado)
}
)
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="ScriptMngr">
<Services>
<asp:ServiceReference Path="~/AjaxWs.asmx" />
</Services>
</asp:ScriptManager>
<div>
<button onclick="executarWs()">Clique aqui</button>
</div>
</form>
</body>
</html>
Now run the Web Site (F5) to see what we've done in action. When we click the button the message "Hello World" will pop up. This alone is very nice already; but, what if we could return objects with properties instead of pure strings and ints? Well, we can!
First, let's create a class in our Web Site. Right click in the App_Code folder below the root folder and choose Add New Item. In the dialog box choose Class. Name it Pessoa.cs and click Ok. Here's the complete code:public class Pessoa {
public string Nome { get; set; }
public string Sobrenome { get; set; }
}
Now let's get back to our Web Service and create a new method that take two parameters and returns an instance of Pessoa. Open the AjaxWs.cs again and add the following code under the HelloWorld method:[WebMethod]
public Pessoa ObterPessoa(string nome, string sobrenome) {
return new Pessoa { Nome = nome, Sobrenome = sobrenome };
}
Now get back to Default.aspx and modify the HelloWorld method call to ObetrPessoa, giving the nome and sobrenome arguments before the callback argument:function executarWs() {
AjaxWs.ObterPessoa(
"Estação",
"ZN",
function(resultado) {
alert(resultado.Nome + " " + resultado.Sobrenome)
}
)
}
Now run the Web Site again and see the result. Awesome! We had nearly zero effort and the possibilities are many with this technology. Thank you and take care.