使用ICallbackEventHandler實現無重新整理回調

來源:互聯網
上載者:User
       在ASP.NET 2.0中,引入了一個稱為"用戶端回調"的功能,利用這個內建的解決方案我們可以輕鬆實現用戶端指令碼和伺服器端代碼間的互動,從而避免了頁面因回傳帶來的頻繁重新整理。用戶端回調本質上就是指通過前端的用戶端指令碼向伺服器端傳遞相應的資料參數,伺服器端再以接受到的參數進行查詢和處理,最後將結果回傳到用戶端進行顯示。在網上已經有蠻多實現無重新整理回調的文章,之前在ASP.NET1.0 用AJAX技術實現過,現在ASP.NET2.0使用ICallbackEventHandler來實現。具體如下:
       前台頁面: 

<body>
    <form id="form1" runat="server">
    <div>
        &nbsp;<input id="txtMessage" style="width: 353px" type="text" />&nbsp;
        <input id="Button1" type="button" value="Call to Server" onclick="CallServer();" />
        <br />
        &nbsp;result:<input id="txtResult" style="width: 442px" type="text" /></div>
    </form>
</body>

        前台指令碼:<script type="text/javascript">
      function CallServer()
      {
          var product = document.getElementById("txtMessage").value;//前台資料傳到幕後處理
          
          //返回幕後處理後的資料到前台,用前台函數ReceiveServerData來接收
          <%= ClientScript.GetCallbackEventReference(this, "product", "ReceiveServerData",null)%>;
      }
      
      function ReceiveServerData(rValue)
      {
         //alert(rValue);
         document.getElementById("txtResult").value = rValue;
     }
     </script>

後台代碼:public partial class testNoRefresh : System.Web.UI.Page, System.Web.UI.ICallbackEventHandler
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    //定義一個字串,回調的結果資訊將儲存在該字串中
    private string CallBackValue = string.Empty;

   

    //引發回調事件處理
    void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument)
    {
        this.CallBackValue = "用戶端在[" + DateTime.Now.ToString() + "]傳送來 [" + eventArgument + "]!";
    }

    //回傳回調結果
    string ICallbackEventHandler.GetCallbackResult()
    {
        return CallBackValue;
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.