ICallbackEventHandler使用

后端:页面需继承ICallbackEventHandler

 protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                string strRefrence = string.Empty;
                strRefrence = Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveDataFromServer", "context"); // 这里ReceiveDataFromServer为客户端接收回调结果的JS方法,含一个传入参数

                string strCallBack = string.Empty;
                strCallBack = "function CallBackToTheServer(arg, context) {" + strRefrence + "};";

                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallBackToTheServer", strCallBack, true);  // CallBackToTheServer,JS方法,发出回调请求

            }

        }
        #region ICallbackEventHandler Members

        private string strTimeFormat;

        public string GetCallbackResult()
        {
            if (strTimeFormat != "" && strTimeFormat == "12")
            {
                return DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss(12小时制)");
            }
            else
            {
                return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss(24小时制)");
            }
        }

        public void RaiseCallbackEvent(string eventArgument)
        {
            strTimeFormat = eventArgument;
        }

        #endregion

前端:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script>
        function ReceiveDataFromServer(valueReturnFromServer) {
            document.getElementById("ServerTime").innerHTML = valueReturnFromServer;
        }

        function GetServerTime(format) {
            CallBackToTheServer(format, "");
        }

    </script>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
       

        <div>
            <asp:Button ID="btnShow12" runat="server" Text="获取服务器时间(12小时制)" OnClientClick="javascript:GetServerTime(12);return false;" /><br />
            <asp:Button ID="btnShow24" runat="server" Text="获取服务器时间(24小时制)" OnClientClick="javascript:GetServerTime(24);return false;" /><br />
            <br />
            <span id="ServerTime"><%= DateTime.Now.ToString("yyyy-MM-dd HHHH:mm:ss") %></span>&nbsp;
        </div>
    </form>
</body>
</html>

 

posted @ 2013-12-18 10:57  Shikyoh  阅读(355)  评论(0编辑  收藏  举报