Monday, October 23, 2006

Calling a webservice from javascript

This is one of the most requested features of ASP.NET Atlas...





By default, Microsoft ASP.NET 2.0 AJAX Extensions
applications cannot call Web services unless explicitly enabled, as explained
below...


1) In the element of the Web site's Web.config file, register the ScriptHandlerFactory class to process calls to .asmx files

---<system.web>
------<httphandlers>
---------<remove path="*.asmx" verb="*">
---------<add type="" path="*.asmx" verb="*">Microsoft.Web.Script.Services.ScriptHandlerFactory" validate="false"/>
------</httphandlers>
---<system.web>

When the proxy class is generated, the proxy class will expose a JavaScript function for each method in the Web service that has been marked with the WebMethod attribute.


2) In the ScriptManager control on the page, define the Web service location by creating an <asp:servicereference> child element and setting its path attribute.


<asp:ScriptManager runat="server" ID="scriptManager">
<services> <asp:servicereference path="~/WebServices/SimpleWebService.asmx" /> </services></asp:ScriptManager>

This setting instructs ASP.NET 2.0 AJAX Extensions where the service is for which to generate a JavaScript proxy.

You can inspect the generated script for the proxy class by entering the following string in the browser address box http://localhost/myService.asmx/js






Setting up the WebService



The web service must be an asmx file and must contain the [ScriptService] attribute . In the sample above we create a webservice file called SimpleWebService.asmx and it will contain the following code...

---[ScriptService]
---public class SimpleWebService : System.Web.Services.WebService{
------[WebMethod]
------public string EchoInput(String input) {
--------- // Method code goes here.
------}
---}





Calling the WebService from JavaScript


sample 1:

function GetNoReturn(){ Samples.AspNet.CallWebService.GetServerTime();}

sample 2:

function GetTime(){
----Samples.AspNet.CallWebService.GetServerTime(OnRequestComplete);
}

function OnRequestComplete(result){
----// Display the result.
----var RsltElem = document.getElementById("Results");
----RsltElem.innerHTML = result;
}

Sample 3:

function Add(a, b){ Samples.AspNet.CallWebService.Add(a, b, OnRequestComplete);}





Client side Error Handling from



function Div(a, b){ Samples.AspNet.CallWebService.Div(a, b, OnRequestComplete, OnRequestFailure);}


function OnRequestFailure(error){
----// Display the error.
----var RsltElem = document.getElementById("Results");
----RsltElem.innerHTML = "Error on the sever: " + error.get_message();
}



For other scenarios see the following link for a more uptodate set of supported scenarios webserviceProxy




Lead by example



The best example explaining all the above can be found here









Sample ASP.NET Atlas project




<!--<Snippet1>-->
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Collections.Generic" %>

<!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>Enter New Employees</title>
<script runat="server">
private List<Employee> EmployeeList;

protected void Page_Load()
{
if (!IsPostBack)
{
EmployeeList = new List<Employee>();
EmployeeList.Add(new Employee(1, "Jump", "Dan"));
EmployeeList.Add(new Employee(2, "Kirwan", "Yvette"));
ViewState["EmployeeList"] = EmployeeList;
}
else
EmployeeList = (List<Employee>)ViewState["EmployeeList"];

EmployeesGridView.DataSource = EmployeeList;
EmployeesGridView.DataBind();
}

protected void InsertButton_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(FirstNameTextBox.Text)
String.IsNullOrEmpty(LastNameTextBox.Text)) { return; }

int employeeID = EmployeeList[EmployeeList.Count-1].EmployeeID + 1;

string lastName = Server.HtmlEncode(FirstNameTextBox.Text);
string firstName = Server.HtmlEncode(LastNameTextBox.Text);

FirstNameTextBox.Text = String.Empty;
LastNameTextBox.Text = String.Empty;

EmployeeList.Add(new Employee(employeeID, lastName, firstName));
ViewState["EmployeeList"] = EmployeeList;

EmployeesGridView.DataBind();
EmployeesGridView.PageIndex = EmployeesGridView.PageCount;
}

protected void CancelButton_Click(object sender, EventArgs e)
{
FirstNameTextBox.Text = String.Empty;
LastNameTextBox.Text = String.Empty;
}

[Serializable]
public class Employee
{
private int _employeeID;
private string _lastName;
private string _firstName;

public int EmployeeID
{
get { return _employeeID; }
}

public string LastName
{
get { return _lastName; }
}

public string FirstName
{
get { return _firstName; }
}

public Employee(int employeeID, string lastName, string firstName)
{
_employeeID = employeeID;
_lastName = lastName;
_firstName = firstName;
}
}

</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" />
<table>
<tr>
<td style="height: 206px" valign="top">
<asp:UpdatePanel ID="InsertEmployeeUpdatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<table cellpadding="2" border="0" style="background-color:#7C6F57">
<tr>
<td><asp:Label ID="FirstNameLabel" runat="server" AssociatedControlID="FirstNameTextBox"
Text="First Name" ForeColor="White" /></td>
<td><asp:TextBox runat="server" ID="FirstNameTextBox" /></td>
</tr>
<tr>
<td><asp:Label ID="LastNameLabel" runat="server" AssociatedControlID="LastNameTextBox"
Text="Last Name" ForeColor="White" /></td>
<td><asp:TextBox runat="server" ID="LastNameTextBox" /></td>
</tr>
<tr>
<td></td>
<td>
<asp:LinkButton ID="InsertButton" runat="server" Text="Insert" OnClick="InsertButton_Click" ForeColor="White" />
<asp:LinkButton ID="Cancelbutton" runat="server" Text="Cancel" OnClick="CancelButton_Click" ForeColor="White" />
</td>
</tr>
</table>
<asp:Label runat="server" ID="InputTimeLabel"><%=DateTime.Now %></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</td>
<td style="height: 206px" valign="top">
<asp:UpdatePanel ID="EmployeesUpdatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="EmployeesGridView" runat="server" BackColor="LightGoldenrodYellow" BorderColor="Tan"
BorderWidth="1px" CellPadding="2" ForeColor="Black" GridLines="None" AutoGenerateColumns="False">
<FooterStyle BackColor="Tan" />
<SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
<PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue" HorizontalAlign="Center" />
<HeaderStyle BackColor="Tan" Font-Bold="True" />
<AlternatingRowStyle BackColor="PaleGoldenrod" />
<Columns>
<asp:BoundField DataField="EmployeeID" HeaderText="Employee ID" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" />
<asp:BoundField DataField="FirstName" HeaderText="First Name" />
</Columns>
<PagerSettings PageButtonCount="5" />
</asp:GridView>
<asp:Label runat="server" ID="ListTimeLabel"><%=DateTime.Now %></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="InsertButton" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</td>
</tr>
</table>
</form>
</body>
</html>
<!--</Snippet1>-->

ASP.NET Ajax - Asynchronous Communication Layer Overview

enable the browser to communicate asynchronously with a server using HTTP or HTTPS. There is a clear separation between the business and data tiers on the server and the presentation tier on the client. The browser can have full control of the presentation tier thus providind a rich and responsive user interface, while the server performs the business and data tier tasks.


The asynchronous communication layer offers the following feature set:


It can invoke methods in Web services implemented as .asmx files.

It can invoke specifically enabled ASP.NET page methods as if they were Web service methods.

It can enable and disable the ability to call Web services or specifically enabled page methods from Microsoft ASP.NET AJAX applications.

It supports a variety of serialization formats for passing data between the browser and the server, including:

  • JavaScript Object Notation (JSON) as a serialization standard for passing data between the browser and the server. This includes JSON serialization for common .NET data types and extensibility for custom JSON serializers.

  • String data.
  • Custom formats that are processed depending on content type that you can specify.

It can optimize Web service interactions by pre-loading and caching JavaScript proxies. The Microsoft ASP.NET AJAX allows the browser to call ASP.NET Web services using JavaScript. It does so by generating a JavaScript proxy that the client uses to communicate with the Web services on the server. For more information, see How To: Call a Web Service from JavaScript..

It provides extensibility points for using different client executors. An executor is the asynchronous communication layer component that functions as an interface between a client Web request and the network or other media. The executor is the key component that makes possible asynchronous communication between client and server. For more information, see XMLHttpExecutor Class. You can write your own executor that plugs into the asynchronous communication layer.

It can be used with Medium trust.

ASP.NET Ajax Overview (Atlas)

perform significant portions of a Web application's page processing in the browser without requiring a round trip to the server. ASP.NET AJAX development technologies integrate ECMAScript (JavaScript) client script libraries with the ASP.NET 2.0 server-based development platform



Why would you use Ajax.NET?


new breed of Web application that has a number of advantages over traditional Web applications.


1. Better performance.
2. Extensive user interface features.
3. Partial-page updating.
4. Asynchronous postbacks.
5. Browser independence.




ASP.NET AJAX Architecture


The complete ASP.NET AJAX architecture consists of both the client script libraries and of server components




ASP.NET AJAX Client Components

The ASP.NET AJAX client script libraries consist of a number of JavaScript (.js) files that provide features for object-oriented development. This was not previously available to developers in a scripting environment, and it enables a new level of consistency and modularity in client scripting. The following layers are included in the ASP.NET AJAX script libraries:

1. A browser compatibility layer. This provides compatibility across most browsers for your ASP.NET AJAX scripts.

2. core services, which include a number of extensions to JavaScript, such as classes, namespaces, event handling, inheritance, data types, and object serialization.

3. An ASP.NET AJAX base class library, which includes components like string builders and extended error handling.

4. A networking layer that handles communication with Web-based services and applications, and managing the asynchronous remote method calls.

5. A UI layer that provides a number of ASP.NET AJAX client capabilities: behaviors, ASP.NET AJAX declarative syntax, UI components, and data binding.

6. A controls layer that creates ASP.NET AJAX-specific controls for client development. These controls can be data-bound, scripted, bound to ASP.NET AJAX behaviors such as drag and drop, and so on. This layer includes controls such as an auto-completion text box, ordinary form controls, a data-bound listview control, and navigation controls.



ASP.NET AJAX Server Components


Consists of ASP.NET Web services and ASP.NET server controls.

All ASP.NET features are available to ASP.NET AJAX applications.

ASP.NET AJAX also includes components in ASP.NET, including Web services and server controls. These components work in conjunction with ASP.NET AJAX client script libraries.

ASP.NET also includes ASP.NET AJAX server controls that resemble ASP.NET server controls, but emit ASP.NET AJAX client script. ASP.NET AJAX server controls simplify the process of producing ASP.NET AJAX client script, and are suitable for developers who want to focus on server-based development. ASP.NET AJAX includes a complete set of server controls that corresponds closely to the existing ASP.NET server controls, such as controls for buttons, labels, options, text boxes, check boxes, hyperlinks, and validation controls. All of these controls will be integrated into Visual Studio so that you can work with them in a designer just as you can with standard ASP.NET server controls.