#眉標= ASP.NET 2.0
#副標=Ajax網頁開發(2)
#大標=使用Client Script Manager製作Ajax風格網頁
#作者=文/王寧疆
=======程式=======
程式1
public partial class _Default : System.Web.UI.Page, ICallbackEventHandler
{
string str; //宣告儲存伺服器執行結果的變數
public string GetCallbackResult()
{
return str; //將執行結果傳送給用戶端
}
public void RaiseCallbackEvent(string eventArgument)
{
//建立SqlDataAdapter類別的物件
SqlDataAdapter da = new SqlDataAdapter(
"select OrderID, CustomerID, OrderDate, RequiredDate from orders where customerid='" + eventArgument + "'",
@"data source=.\sqlexpress;initial catalog=northwind;integrated security=True");
DataSet ds = new DataSet(); //建立DataSet類別的物件
da.Fill(ds); //查詢資料庫中的訂單記錄,並將查詢結果填入DataSet類別的物件中
str=ds.GetXml(); //將查詢結果轉型成字串並存入str變數中
}
}
=======程式=======
=======程式=======
程式2
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) //製作網頁第一次執行必須執行的程式碼
{
ClientScriptManager csm = Page.ClientScript; //取得ClientScriptManager類別的物件
string str = csm.GetCallbackEventReference(this, "args", "ReceiveServerData",
""); //指定用戶端負責處理伺服器傳回結果的函數名稱為ReceiveServerData
string strCallback = "function CallServer(args,context){" + str +
";}"; //將呼叫GetCallbackEventReference的結果準備成植入用戶端的Script的內容
csm.RegisterClientScriptBlock(this.GetType(), "CallServer", strCallback,
true); //將準備好的Script植入用戶端
DropDownList1.Attributes.Add("onchange", "return SendCustomerID();"
); //設定DropDownList控制項被選擇的內容改變要呼叫SendCustomerID函數
//建立SqlDataAdapter類別的物件
SqlDataAdapter da = new SqlDataAdapter("select customerid from customers",
@"data source=.\sqlexpress;initial catalog=northwind;integrated security=True");
DataSet ds = new DataSet(); //建立DataSet類別的物件
da.Fill(ds); //查出Customers資料表中的CustomerID
DropDownList1.DataSource=ds; //設定DropDownList控制項要顯示查詢得到的CustomerID
DropDownList1.DataTextField="customerid"; //設定DropDownList控制項顯示的欄位
DropDownList1.DataValueField="customerid"; //設定DropDownList控制項私藏的欄位
DropDownList1.DataBind(); //命令DropDownList控制項顯示資料
}
}
=======程式=======
=======程式=======
程式3
function ReceiveServerData(args, context)
{
}
=======程式=======
=======程式=======
程式4
WebForm_DoCallback
('__Page',args,ReceiveServerData,"",null,false)
=======程式=======
=======程式=======
程式5
=======程式=======
=======程式=======
程式6
=======程式=======
=======程式=======
程式7
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Browser.SupportsCallback &&
Request.Browser.SupportsXmlHttp)
{
...
}
}
=======程式=======
=======程式=======
程式8
=======程式=======
=======程式=======
程式9
protected void Page_Load(object sender, EventArgs e)
{
Ajax.Utility.RegisterTypeForAjax(typeof(WebForm1));
//初始化網頁
}
=======程式=======
=======程式=======
程式10
[Ajax.AjaxMethod()]
public string GetQuote()
{
}
=======程式=======
=======程式=======
程式11
WebForm1.GetQuote(GetQuote_CallBack);
//呼叫WebForm1網頁定義的GetQuote方法
=======程式=======
=======程式=======
程式12
function GetQuote_CallBack(response)
{
document.all.lblQuote.innerHTML=response.value;
//取回伺服器傳回的結果,並顯示到網頁上
}
=======程式=======