1、创建Web服务
添加Web服务,生成TerritoriesService.asmx和TerritoriesService.cs文件。
asmx很简单,只有一行WebService指令。cs源文件如下,包括Web方法,public List<Territory> GetTerritoriesInRegion(int regionID):根据regionID的值,查询Northwind中的表Territories,获取TerritoryID和TerritoryDescription内容,返回List<Territory>。
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Data;
/// <summary>
/// Summary description for TerritoriesService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class TerritoriesService : System.Web.Services.WebService {
public TerritoriesService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public List<Territory> GetTerritoriesInRegion(int regionID)
{
SqlConnection con = new SqlConnection(
System.Configuration.ConfigurationManager.ConnectionStrings["Northwind"].ConnectionString);
SqlCommand cmd = new SqlCommand(
"SELECT * FROM Territories WHERE RegionID=@RegionID", con);
cmd.Parameters.Add(new SqlParameter("@RegionID", SqlDbType.Int, 4));
cmd.Parameters["@RegionID"].Value = regionID;
List<Territory> territories = new List<Territory>();
try
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
territories.Add(new Territory(
reader["TerritoryID"].ToString(),
reader["TerritoryDescription"].ToString()));
}
reader.Close();
}
catch (SqlException err)
{
// Mask errors.
throw new ApplicationException("Data error.");
}
finally
{
con.Close();
}
return territories;
}
}
public class Territory
{
public string ID;
public string Description;
public Territory(string id, string description)
{
this.ID = id;
this.Description = description;
}
public Territory() { }
}
2、创建Web Form,WebServiceCallback,调用Web 服务,该Web表单中有两个DropDownList,第一个列表获取Northwind数据库中表Region的内容,第二个表中显示RegionID对应的territory信息。
第一个列表中通过onchange特性与客户端javascript函数onChange="GetTerritories(this.value)来触发事件,使用web服务来写触发事件,对执行完web方法后返回的值,通过OnRequestComplete(result)将返回值绑定到第二个dropdownlist中。
注意在aspx文件的开头加上 EnableEventValidation="false"。
aspx的内容如下:
View Code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebServiceCallback.aspx.cs" Inherits="WebServiceCallback" EnableEventValidation="false" %>
<!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></title>
<script type="text/javascript">
function GetTerritories(regionID)
{
TerritoriesService.GetTerritoriesInRegion(regionID,
OnRequestComplete, OnError);
}
function OnRequestComplete(result)
{
var lstTerritories = document.getElementById("lstTerritories");
lstTerritories.innerHTML = "";
for (var n = 0; n < result.length; n++)
{
var option = document.createElement("option");
option.value = result[n].ID;
option.innerHTML = result[n].Description;
lstTerritories.appendChild(option);
}
}
function OnTimeout(result)
{
var lbl = document.getElementById("lblInfo");
lbl.innerHTML = "<b>Request timed out.</b>";
}
function OnError(result)
{
var lbl = document.getElementById("lblInfo");
lbl.innerHTML = "<b>" + result.get_message() + "</b>";
// Can also use this code.
//lbl.innerHTML += result.get_stackTrace();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/TerritoriesService.asmx" />
</Services>
</asp:ScriptManager>
<div style="font-family:Verdana;font-size:small ">
Choose a Region, and then a Territory:<br />
<br />
<asp:DropDownList ID="lstRegions" Runat="server" Width="210px" DataSourceID="sourceRegions" DataTextField="RegionDescription" DataValueField="RegionID" onChange="GetTerritories(this.value);">
</asp:DropDownList>
<asp:DropDownList ID="lstTerritories" Runat="server" Width="275px">
</asp:DropDownList><br />
<br />
<br />
<asp:Button ID="cmdOK" Runat="server" Text="OK" Width="50px" OnClick="cmdOK_Click" /><br />
<br />
<asp:Label ID="lblInfo" runat="server"></asp:Label>
<asp:SqlDataSource ID="sourceRegions" runat="server" ProviderName="System.Data.SqlClient" ConnectionString="<%$ ConnectionStrings:Northwind %>" SelectCommand="SELECT 0 As RegionID, '' AS RegionDescription UNION SELECT RegionID, RegionDescription FROM Region" ></asp:SqlDataSource>
</div>
</form>
</body>
</html>
aspx.cs内容很少,只是点击ok按钮后,显示territory的id。
aspx.cs View Code
public partial class WebServiceCallback : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void cmdOK_Click(object sender, EventArgs e)
{
lblInfo.Text = "You selected territory ID #" + Request.Form["lstTerritories"];
// Reset the region list box (because the territory list box will be empty).
lstRegions.SelectedIndex = 0;
}
}
运行该程序,初始界面如下:
运行结果如下: