在ASP.NET Atlas中調用Web Service——直接在ASPX頁面上暴露Web Method

來源:互聯網
上載者:User
作者: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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.