之前在网上找了很久,也没有找到比较好的方法,大都说是通过后台接收 Request["__EventTarget"] 和 Request["__EventArgument"]来实现,可我总觉得上面的方法有点别扭。再或者就是在前端放置一个runat="server"的button控件,然后将控件的Visible属性设为false,再通过ClientScript.GetPostBackEventReference在客户端生成调用方法来激发客户端事件。第二种方法我觉得还是可以的,第一种方法我觉得风险比较大。 微软的官方文档似乎并没有提供这样的用法(也许是我没查到),只是大家分析了asp.net的客户端调用后给出的结果,系统升级存在一定风险。如果有一天微软改变了生成在客户端脚本中的变量名称或方法构造,是不是这个项目要重新来做呢?
经过我的查证有一个方法更好用一些,而且更加简单,请看代码:
客户端:
代码
<%
@ Page Language
=
"
C#
"
AutoEventWireup
=
"
true
"
CodeBehind
=
"
WebForm3.aspx.cs
"
Inherits
=
"
WebApplication1.WebForm3
"
%>
<! 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 >
</ head >
< body >
< form id = " form1 " runat = " server " >
< div >
< input id = " Button1 " type = " button " value = " button " onclick = " <%=ClientScript.GetPostBackEventReference(this, " inc " ,true) %> " />
< asp:TextBox ID = " TextBox1 " runat = " server " ></ asp:TextBox >
</ div >
</ form >
</ body >
</ html >
<! 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 >
</ head >
< body >
< form id = " form1 " runat = " server " >
< div >
< input id = " Button1 " type = " button " value = " button " onclick = " <%=ClientScript.GetPostBackEventReference(this, " inc " ,true) %> " />
< asp:TextBox ID = " TextBox1 " runat = " server " ></ asp:TextBox >
</ div >
</ form >
</ body >
</ html >
服务器端:
代码
using
System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class WebForm3 : System.Web.UI.Page,IPostBackEventHandler
{
protected void Page_Load( object sender, EventArgs e)
{
}
public void RaisePostBackEvent( string eventArgument)
{
if (eventArgument == " inc " )
TextBox1.Text = DateTime.Now.ToString();
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class WebForm3 : System.Web.UI.Page,IPostBackEventHandler
{
protected void Page_Load( object sender, EventArgs e)
{
}
public void RaisePostBackEvent( string eventArgument)
{
if (eventArgument == " inc " )
TextBox1.Text = DateTime.Now.ToString();
}
}
}
上面的代码已经实现了客户端调用服务器代码的功能了。只是让page继承了一下IPostBackEventHandler接口,就可以了。