圖3-6 除數為0導致本次除法失敗
讓我們先從服務器端的Web Service入手。將該Web Service命名為MathService,并在其中定義了一個名為Divide()的方法,用來執行除法操作。Divide()方法所接受的兩個參數分別代表被除數和除數,其邏輯非常簡單,代碼如下:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class MathService : System.Web.Services.WebService
{
[WebMethod]
public int Divide(int a, int b)
{
return (int)(a / b);
}
}
這里有必要再次提醒一下,Web Service類要添加[ScriptService]屬性,其中需要暴露給客戶端的方法也要添加[WebMethod]屬性——這些都是允許從客戶端調用該Web Service代理的必要條件。
在ASP.NET頁面中,添加ScriptManager控件以及上述Web Service的引用:
<asp:ScriptManager ID="sm" runat="server">
<Services>
<asp:ServiceReference Path="Services/MathService.asmx" />
</Services>
</asp:ScriptManager>
然后在ASP.NET頁面中定義程序的界面:
<input id="tbA" type="text" style="width: 40px" /> /
<input id="tbB" type="text" style="width: 40px" /> =
<input id="btnInvoke" type="button" value="?"
onclick="return btnInvoke_onclick()" />
<div id="result"></div>
其中前兩個<input />(id分別為tbA和tbB)用來讓用戶輸入被除數和除數;第三個<input />(id為btnInvoke)則作為按鈕(type="button")用來觸發對服務器端Web Service的調用,并顯示除法完成后的商;下面id為result的<div />用來顯示可能出現的異常信息。
文章來源于領測軟件測試網 http://www.kjueaiud.com/