c# 通过ICallbackEventHandler 实现页面无刷新

来源:互联网 发布:旅游的软件哪个好 编辑:程序博客网 时间:2024/05/21 16:17

创建服务器回调方法

在服务器代码中,必须创建一个实现 RaiseCallbackEvent 方法的方法和一个实现 GetCallbackResult 方法的方法。RaiseCallbackEvent 方法接受单个字符串参数,而不是通常用于事件处理程序的常见的两个参数。该方法的部分内容可能与下面的代码示例类似。

 

public void RaiseCallbackEvent(String eventArgument)
{
 
}

GetCallbackResult 不接受参数并返回一个字符串。该方法的部分内容可能与下面的代码示例类

public string GetCallbackResult()
{
    return aStringValue;
}

 

 

Aspx:

<%@ PageLanguage="C#"AutoEventWireup="true"CodeBehind="WebForm1.aspx.cs"Inherits="WebTest.WebForm1"%>

<%@ ImportNamespace="System.Web.UI"%>

<!DOCTYPE html PUBLIC "-//W3C//DTDXHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<script type="text/jscript">

function CallServer(inputcontrol,context)

{

    //回调还没有处理完全时其预先加载的显示值

    context.innerHTML = "加载中...";

    //这里的arg传递到后台RaiseCallbackEvent(string eventArgument)方法中去

    arg= inputcontrol.value;

    //获取一个对客户端函数的引用  调用该函数时 将启动一个对服务器端事件的客户端回调

   

   

    //各参数含义:

    //this指当前页面

    //arg 客户端传递给服务端RaiseCallbackEvent的值

    //ReceiveServerData客户端的一个js函数,服务器会返回值传递给这个函数,做为这个函数的参数。

    //context脚本的结果传回客户端事件处理程序

    <%=ClientScript.GetCallbackEventReference(this,"arg", "ReceiveServerData","context")%>

}

function ReceiveServerData(result,context)

{

    context.innerHTML=result;

}

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >

<head id="Head1" runat="server">

    <title>无标题页</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <input id="Text1" type="text" />

        <input id="Button1" type="button" value="button" onclick="CallServer(Text1,Label1);"/>

    </div>

    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

    </form>

</body>

</html>

 

Aspx.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

namespace WebTest

{

    publicpartial class WebForm1 : System.Web.UI.Page,ICallbackEventHandler

    {

        stringtestvalue = "";

        protectedvoid Page_Load(object sender, EventArgs e)

        {

 

        }

 

        #region ICallbackEventHandler 成员

 

        publicstring GetCallbackResult()

        {

            returntestvalue;

        }

 

        publicvoid RaiseCallbackEvent(string eventArgument)

        {

            testvalue= eventArgument + "1";

        }

 

        #endregion

    }

}


原创粉丝点击