UpdatePanel 簡化部分更新,但若需呼叫耗時 Web Service,客戶端腳本非同步呼叫可避免瀏覽器凍結。本文示範建立 Web Service 並透過 JavaScript 呼叫,搭配 UpdatePanel 顯示結果。
NorthwindConnectionString 連線字串ProductQueryService.asmx。System.Data、System.Data.SqlClient、System.Configuration、System.Web.Script.Services。[ScriptService] 允許客戶端呼叫。GetProductQuantity:查詢庫存並 Thread.Sleep(3000) 模擬延遲。[WebMethod]
public string GetProductQuantity(string productID)
{
// ... ADO.NET 查詢 UnitsInStock ...
System.Threading.Thread.Sleep(3000);
return unitsInStock;
}
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/ProductQueryService.asmx" />
</Services>
</asp:ScriptManager>
<script type="text/javascript">
function callService() {
var productId = $get('ProductIdTextBox').value;
ProductQueryService.GetProductQuantity(productId, onSuccess, onFailure);
}
function onSuccess(result) {
$get('ResultLabel').innerHTML = '庫存: ' + result;
// 可選:觸發 UpdatePanel 更新其他區塊
__doPostBack('UpdatePanelTrigger', '');
}
function onFailure(error) { alert(error.get_message()); }
</script>
UpdatePanel 負責複雜區塊局部更新,Web Service 處理純資料查詢,職責分離。結合 ScriptService、客戶端 Proxy 與 UpdatePanel,可構建回應迅速、職責清晰的 AJAX 應用。