在ASP.NET Atlas中調用Web Service——在頁面載入時調用Web Service

來源:互聯網
上載者:User
作者:Dflying Chen (http://dflying.cnblogs.com/ )

很多時候我們需要在頁面載入以後立刻調用一些Web Service,比如一個用戶端的Atlas ListView會在載入後立刻得到初始化的填充資料。雖然這可以使用Atlas的InitialData控制項完成,但對於其它的一些要求,比如在頁面載入後立刻執行一段Atlas指令碼(其中用到了Atlas對JavaScript的擴充),我們仍需要一個頁面載入的事件來觸發這些操作。

很多朋友採用如下的兩種方法:

  1. 直接在頁面的Script段中書寫要執行的指令碼。
  2. 在頁面的onload JavaScript事件處理方法中書寫。

這些都是不正確的方式,會有錯誤發生,原因很簡單:Atlas的用戶端實現也是一段JavaScript,需要先執行一次才可以工作,而上述兩種方法的語句都是在Atlas用戶端實現被初始化前啟動並執行,自然會導致錯誤。

Atlas充分意識到了這個需求,提供了Framework內部的OnLoad事件,該事件將在Atlas Framework初始化以後被引發。想捕獲這個事件,您需要在頁面的Atlas XML Script中聲明:

<page xmlns:script="http://schemas.microsoft.com/xml-script/2005">
  <components>
    <application id="application" load="OnApplicationLoad" />
  </components>
</page>

其中application作為當前啟動並執行Atlas程式的引用,提供了一個load事件,這樣我們通過指定它的事件處理函數,即可在Atlas Framework初始化之後執行我們的代碼。

下面來看一個例子,Web Service如下,還是簡單的兩個數相加:

[WebMethod]
public int AddInt(int int1, int int2)
{
    return int1 + int2;
}

然後ASPX頁面中添加ScriptManager並對上述Web Service進行引用:

<atlas:ScriptManager ID="scriptManager" runat="server" EnableScriptComponents="true">
    <Services>
        <atlas:ServiceReference Path="SimpleWebService.asmx" />
    </Services>
</atlas:ScriptManager>

頁面上再添加兩個input用來提供兩個加數:

<input id="value1" type="text" value="1" />
<input id="value2" type="text" value="2" />

加上捕獲Atlas Framework load事件的XML Script定義:

<script type="text/xml-script">
    <page xmlns:script="http://schemas.microsoft.com/xml-script/2005">
      <components>
        <application id="application" load="OnApplicationLoad" />
      </components>
    </page>
</script>

下面是事件處理函數以及相應的Callback,可以看到我們應用了三種Atlas Framework提供的擴充:

  1. $()方法,等同於document.getElementById()
  2. Sys.UI.TextBox類,封裝了HTML的input元素
  3. 對Web Service調用的Mashup
function OnApplicationLoad() 
{
    var value1 = new Sys.UI.TextBox($('value1'));
    var value2 = new Sys.UI.TextBox($('value2'));
    Dflying.SimpleWebService.AddInt(
        value1.get_text(),
        value2.get_text(),
        OnComplete
    );
    return false;
}

function OnComplete(result) 
{
    alert(result);
}

運行結果,沒有任何問題:

本執行個體的原始碼可以在此下載:http://files.cnblogs.com/dflying/ApplicationLoadEventDemo.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.