ASP.NET实现Ajax效果:动态刷新显示输入文字

本文介绍了一个 ASP.NET 页面如何使用回调机制与服务器进行交互。通过客户端 JavaScript 调用服务器端方法并接收结果,展示了回调机制的基本原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前台页面:

 

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!--<%@ Implements Interface="System.Web.UI.ICallbackEventHandler" %>-->

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    
<title>无标题页</title>

    
<script type="text/javascript">
      
<!--定义客户端发送回调函数-->
      
function CallServer()
      {
          
var txt = document.forms[0].txtValue.value;              
          
<!--CallServer(product, "");-->      
          
<%= ClientScript.GetCallbackEventReference(this"txt""ReceiveServerData",null)%>;
      }
      
<!--定义客户端接受回调结果函数-->
      
function ReceiveServerData(rValue)
      {          
         Result.innerText 
= rValue;         
      }
    
</script>

</head>
<body>
    
<form id="form1" runat="server">
    
<div>
    
<table width =100% >
    
<tr>
    
<td width=50><input type=text  ID=txtValue onkeydown='CallServer()'/></td>
    
<td><button ID=btnOK OnClick="CallServer()">刷新</button></td>
    
</tr>
    
<tr>
    
<td colspan=2 bgcolor=aqua><span ID = "Result"></span></td>
    
</tr>
    
</table>
    
</div>
    
</form>
</body>
</html>

 

后台代码:

 

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

//继承ICallbackEventHandler接口
public partial class _Default : System.Web.UI.Page,System.Web.UI.ICallbackEventHandler
{
    
//定义返回字符串变量
    private string CallBackValue = string.Empty;

    
protected void Page_Load(object sender, EventArgs e)
    {
        
    }
    
//将检索到的数据返回该控件
    string ICallbackEventHandler.GetCallbackResult()
    {
        
return CallBackValue + ",ok!";
    }
    
//创建服务器代码回调方法
    
//在服务器代码中,必须创建实现 RaiseCallbackEvent 接口的方法。
    
//该方法使用一个字符串参数,而不是事件处理程序常用的那两个常见参数。
    
//该方法也返回一个字符串,不过不是在本函数中,而是在GetCallbackResult()函数中返回。
    void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument)
    {
        
this.CallBackValue = eventArgument;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值