js 客户端回调功能实现(备忘)

使用js不用ajax 也可以实现,页面无刷新回调功能

View Code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="_Default2" %>

<!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 getWriteText() {
            var name = document.forms[0].TextBox2.value;//输入的值
            var name2 = document.forms[0].TextBox2.value;//输出的值
            UserCallBack(name,"");
        }
        function getValueFormServer(TextBox1, content) {
            document.forms[0].TextBox1.value = TextBox1;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:TextBox ID="TextBox2" Width="600px" runat="server"></asp:TextBox>
    <asp:TextBox ID="TextBox1" Width="600px" runat="server"></asp:TextBox>
    <input id="Button1" type="button" value="button" onclick="getWriteText()" />
    </form>
</body>
</html>

后台代码

View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default2 : System.Web.UI.Page, ICallbackEventHandler
{
    private string _callBackResult = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        //加载,创建js函数
        string cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "getValueFormServer", "content");
        string cbScript = "function UserCallBack(arg,content){" + cbReference + ";}";
        Page.ClientScript.RegisterClientScriptBlock(GetType(), "UserCallBack", cbScript, true);
    }
    public void RaiseCallbackEvent(string enentArg) 
    {
        //处理客户端异步请求
        _callBackResult = "您输入的是:"+enentArg;
    }
    public string GetCallbackResult()
    {
        //返回处理值
        return _callBackResult;
    }
}

这里需要实现System.Web.UI.ICallbackEventHandler 接口哦,并且要实现RaiseCallbackEvent和GetCallbackResult

原文地址:https://www.cnblogs.com/ywtk/p/2891114.html