日期:2011-04-02  浏览次数:20419 次

在Asp.Net中经常要用到脚本回调和页面间的传值,下面是关于ScriptCallBack和Server.Transfer简单的示例代码

WebForm1.aspx
给Head中增加__doPostBack脚本,如果页面含有HyperLink等按钮控件,该脚本和2个隐藏控件"__EVENTTARGET"和"__EVENTARGUMENT"由FrameWork自动生成,若没有需要手动添加

<SCRIPT language="javascript">
<!--
function __doPostBack(eventTarget, eventArgument) {
    var theform;
    if (window.navigator.appName.toLowerCase().indexOf("netscape") > -1) {
        theform = document.forms["Form1"];//注意此处的FormID
        } else {
        theform = document.Form1;//还有此处
    }
    theform.__EVENTTARGET.value = eventTarget.split("$").join(":");
    theform.__EVENTARGUMENT.value = eventArgument;
    theform.submit();
}
// -->
</SCRIPT>

<form id="Form1" method="post" runat="server">
<INPUT type="hidden" name="__EVENTTARGET" >
<INPUT type="hidden" name="__EVENTARGUMENT" >
<A href="javascript:__doPostBack('ScriptCallBack','ScriptCallBack')">ScriptCallBack</A>
<ASP:TEXTBOX id="TextBox1" style="Z-INDEX: 101; LEFT: 112px; POSITION: absolute; TOP: 152px" runat="server">sometext</ASP:TEXTBOX>

C#
WebForm1.aspx.cs
private void Page_Load(object sender, System.EventArgs e)
{
    if (IsPostBack)
        if (Request.Form["__EVENTARGUMENT"]== "ScriptCallBack")
            Server.Transfer("WebForm2.aspx", true);//第二个参数指示是否保留页面的Form和QuerryString的值
}

WebForm2.aspx.cs
private void Page_Load(object sender, System.EventArgs e)
{
    if(this.Context.Handler != sender)
        Response.Write(Request.Form["TextBox1"]);
}

VB.NET
WebForm1.aspx.vb
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    If IsPostBack Then
        If Request.Form("__EVENTARGUMENT") = "ScriptCallBack" Then
            Server.Transfer("WebForm2.aspx", True)'第二个参数指示是否保留页面的Form和QuerryString的值
        End If
    End If
End Sub

WebForm2.aspx.vb
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    If Not Me.Context.Handler Is sender Then
        Response.Write(Request.Form("TextBox1"))
    End If
End Sub