In part 3 of 3, of this tutorial we will learn how to handle complex types, create and use paging methods, and use the AutoCompleteExtender and the ASP.NET AJAX Toolkit.
Learn How to Handle Complex Types
These complex types that are accepted or returned by a Web service are automatically exposed through a JavaScript proxy. Nested complex types are not directly accessible on the client site unless the GenerateScriptType attribute is applied to the service.
Here is an example of client-side code that invokes an address object defined in a Model namespace. It fills it with updated data and assigns it to a StudentDetails object’s Address property. Then it’s passed by StudentDetails to the Web service for processing.
function UpdateAddress()
{
var stud = new Model.StudentDetails();
stud.StudentID = $get("hidStudentID").value;
stud.Address = CreateAddress();
InterfaceTraining.DemoService.UpdateAddress(stud,OnWSUpdateComplete);
}
function CreateAddress()
{
var addr = new Model.Address();
addr.Street = $get("txtStreet").value;
addr.City = $get("txtCity").value;
addr.State = $get("txtState").value;
return addr;
} function OnWSUpdateComplete(result)
{
alert("Update " + ((result)?"succeeded":"failed")+ "!");
} |
Learn How to Create and Use Paging Methods
Let’s say there is a case where a page needs to retrieve data that will never be used or shared by other pages. Although Web services provide ways to expose re-usable services to a variety of clients including ASP.NET AJAX pages, try making a .asmx file to allow the page to access the data even though it may seem a little excessive considering the service is only used by a single page.
I just signed up at Server Intellect and couldn't be more pleased with my Windows Server! Check it out and see for yourself.
Another way is to provide mechanisms for making Web service calls without creating .asmx files. This technique is referred to as “page methods”. A page method is a static method embedded directly in a page or code beside file that have the WebMethod attribute applied to it. Then by calling a JavaScript object named PageMethods through a WebMethod attribute it will get dynamically created at runtime. What the PageMethods object is doing is actng like a proxy that guards you from the JSON serialization/deserialization process.
| <asp:ScriptManager ID="smScriptManager" runat="server" EnablePageMethods="true"> </asp:ScriptManager> |
In order to use the PageMethods object you must set the ScriptManager’s EnabledPageMethods property to true.
Below the methods retrieve data from a business layer class located in the App_Code folder that defines two page methods in an ASP.NET code beside class.
[WebMethod]
public static Student[] GetStudentsByUniversity(string university)
{
return Biz.BAL.GetStudentsByUniversity(university);
} [WebMethod]
public static Student[] GetStudentsByID(string id)
{
return Biz.BAL.GetStudentsByID(id);
} |
If you're ever in the market for some great Windows web hosting, try Server Intellect.We have been very pleased with their services and most importantly, technical support.
When calling a Web Method you need to reference the PageMethod class followed by the name of the method and any necessary data that should be passed. Here is an example of calling page methods with the PageMethods Javascript object:
function GetStudentsByUniversity()
{
var university = $get("txtUniversity ").value;
PageMethods.GetStudentsByUniversity(university, OnWSRequestComplete);
}
function GetStudentByID()
{
var studID = $get("txtStudentID").value;
PageMethods.GetStudentsByID(studID, OnWSRequestComplete);
} function OnWSRequestComplete(results)
{
var searchResults = $get("searchResults"); searchResults.control.set_data(results);
if (results != null) GetMap(results[0].University,results);
} |
TheThe PageMethods object is very similar to using JavaScript proxy object. First you must specify all of the parameter data that should be passed to the page method and then define the callback function that’s called when the asynchronous call returns. A failure callback can also be specified.
Learn How to Use the AutoCompleteExtender and the ASP.NET AJAX Toolkit
The ASP.NET AJAX Toolkit offers several pretty cool controls that can be used to access Web services. One useful control is AutoCompleteExtender. This can be used to call Web Services and show data in pages without writing any JavaScript code at all.
The AutoCompleteExtender control primarily is used to extend functionality of a textbox and help users easily locate data they’re looking for. You may have seen this done before. Once you type in the textbox the control query’s a Web service and shows the results below the textbox dynamically.
We moved our Web sites to Server Intellect and have found them to be incredibly professional. Their setup is very easy and we were up and running in no time.
When using the AutoCompleteExtender in an ASP.NET AJAX page, it is required that the AjaxControlToolkit.dll assembly is added in the Web site’s bin folder. After the toolkit assembly has been added, reference it n the web.config so the controls it contains are available to every page within the application.
Here is an example of how this can be done:
| <add namespace="AjaxControlToolkit" assembly="AjaxControlToolkit" tagPrefix="ajaxToolkit"/> |
In a case where you need to use a control on a specific page you can reference it by adding the Reference directive like this example:
| <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %> |
Here is example code of an ASP.NET AutoCompleteExtender control that calls a Web service after the Website has been configured to use the ASP.NET AJAX Toolkit.
<ajaxToolkit:AutoCompleteExtender ID="extTxtStudentID" runat="server"
MinimumPrefixLength="1"
ServiceMethod="GetStudentIDs"
ServicePath="~/StudentsService.asmx"
TargetControlID="txtStudentID" /> |
Notice that the AutoCompleteExtender has several different properties including standard ID and runat properties which are usually found on server controls. The control also includes how many characters you might want to set it to before the Web service is queried for the data. Be careful setting the MinimumPrefixLength property because each time a user types a character in the textbox the Web service will be called to search for values that match the characters. The WebService to call and the target Web Method are defined using the ServicePath and ServiceMethod properties. Lastly, the TargetControlID property just identifies which textbox to associate the AutoCompleteExtender control with.
Server Intellect offers Windows Hosting Dedicated Servers at affordable prices. I'm very pleased!
The Web Service being called must have the ScriptService attribute and the target Web Method must accept two parameters named “prefixText” and “count”. The prefixText parameter represents the characters typed and count parameter represents how many items to return.
Below is example code of the GetStudentsIDs Web Method called by the AutoCompleteExtender control. It then calls a business layer method that in turn calls a data layer method that then handles the filtering of the data and returns the matching results.
[WebMethod] public string[] GetStudentIDs(string prefixText, int count)
{
return Biz.BAL.GetStudentIDs(prefixText, count);
} table> |
Above filters the data sent from the AutoCompleteExtender control. Below filters the results based upon the end user input.
public static string[] GetCustomerIDs(string prefixText, int count)
{
//Customer IDs cached in _CustomerIDs field to improve performance
if (_CustomerIDs == null)
{
List ids = new List();
//SQL text used for simplicity...recommend using sprocs
string sql = "SELECT CustomerID FROM Customers";
DbConnection conn = GetDBConnection();
conn.Open();
DbCommand cmd = conn.CreateCommand();
cmd.CommandText = sql;
DbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
ids.Add(reader["CustomerID"].ToString());
}
reader.Close();
conn.Close();
_CustomerIDs = ids.ToArray();
}
int index = Array.BinarySearch(_CustomerIDs, prefixText, new CaseInsensitiveComparer());
//~ is bitwise complement (reverse each bit)
if (index < 0) index = ~index;
int matchingCount;
for (matchingCount = 0; matchingCount < count && index + matchingCount < _CustomerIDs.Length; matchingCount++)
{
if (!_CustomerIDs[index + matchingCount].StartsWith(prefixText, StringComparison.CurrentCultureIgnoreCase))
{
break;
}
}
String[] returnValue = new string[matchingCount];
if (matchingCount > 0)
&nb {
Array.Copy(_CustomerIDs, index, returnValue, 0, matchingCount);
}
return returnValue;
} |
In this tutorial we have discussed how ASP.NET AJAX provides support for calling Web Services without writing a lot of JavaScript code to handle the request and response messages. The ASP.NET AJAX enabled Web services process JSON messages and define JavaScript proxies using the ScriptManager control. We now know how JavaScript proxies can be used to call Web Services, handle simple and complex types and deal with failures. Lastly, the AutoCompleteExtender control can provide assistance to end users as they type.
Server Intellect assists companies of all sizes with their hosting needs by offering fully configured server solutions coupled with proactive server management services. Server Intellect specializes in providing complete internet-ready server solutions backed by their expert 24/365 proactive support team.