作者:Dflying Chen(http://dflying.cnblogs.com/)
前面的一系列的文章都是直接調用單獨的一個Web Service,而在實際項目開發中,特別是在對現有的項目轉換中,把頁面中的邏輯再提取到專門的Web Service中往往會帶來相當多的工作。Atlas充分考慮到了這一點,允許您將伺服器端的public方法加上[WebMethod]屬性以允許用戶端JavaScript的直接調用。
想允許用戶端直接調用定義在ASPX頁面中的方法,您需要指定該方法為public,並且添加[WebMethod]屬性,例如如下定義在ASPX檔案中的伺服器端方法:
<script runat="server">
[WebMethod]
public int AddInt(int int1, int int2)
{
return int1 + int2;
}
</script>
在用戶端,Atlas將為您Mashup出一個AddInt的JavaScript方法,存在於一個特殊的命名空間PageMethods中,這樣您就可以通過PageMethods.AddInt()調用上面的方法了。
同時,將WebMethod定義到ASPX頁面中,您還可以在該方法中訪問一切頁面上的伺服器端控制項的值和ViewState,並且整個頁面的的生存周期將和傳統的ASP.NET頁面PostBack一樣,諸如Page_Load等方法均會被調用,可以讓我們對頁面有更強的訪問能力。不過這樣也帶來了效能上的折扣,因為每次調用Web Method的時候都會把頁面上的ViewState和控制項的值傳回給伺服器,並且伺服器端處理整個頁面的生存周期將要比僅僅處理一個純粹的定義在ASMX中的Web Method要複雜的多。所以這裡我推薦儘可能的使用純粹的Web Service,請參考:在Atlas伺服器端實現中推薦使用Web Service而不是Page Method。
下面來看一個執行個體,首先來定義在ASPX中的WebMethod,可以看到這裡不單單求兩個數的和,還訪問了一個頁面上的伺服器端TextBox的值:
<script runat="server">
[WebMethod]
public string AddInt(int int1, int int2)
{
return (int1 + int2).ToString() + string.Format("\r\nAnd the Server TextBox's Text is '{0}'.", tbServer.Text);
}
</script>
然後是頁面的ScriptManager,這裡無需添加任何引用了:
<atlas:ScriptManager ID="scriptManager" runat="server" />
然後兩個用來輸入加數的input以及用來觸發伺服器調用的input:
<input id="value1" type="text" value="1" />
<input id="value2" type="text" value="2" />
<input id="btnAdd" type="button" value="Add!" onclick="return btnAdd_onclick()" />
還有一個伺服器端TextBox:
<asp:TextBox ID="tbServer" runat="server" Text="Server control"></asp:TextBox>
最後是JavaScript調用,注意PageMethods這個內建的命名空間:
function btnAdd_onclick() {
PageMethods.AddInt(
$('value1').value,
$('value2').value,
OnComplete
);
}
function OnComplete(result)
{
alert(result);
}
瀏覽器中運行,輸入兩個加數,然後在Server端的TextBox中輸入一些字元,點擊Add,可以看到Server端的TextBox的值卻是被訪問到了:
這是Fiddler截獲的網路傳輸,可以看到ViewState和TextBox都被傳回了Server:
該執行個體程式的原始碼可以在此下載:http://files.cnblogs.com/dflying/WebMethodOnPage.zip