asp.net - ASP.NET 如何知道在回发期间触发哪个事件?

标签 asp.net webforms

在回发期间,__EVENTTARGET 表单变量保存发出回发的 控件的名称。如果控件支持多个服务器端事件,ASP.NET 如何知道该控件触发哪个事件?

最佳答案

正如 Wiktor 所提到的,ASP.Net 中的许多控件已经为您构建了,以便您以某些方式使用;按钮单击,文本更改,所选索引更改 - 这些控件已构建用于执行某些操作,which is why they work the way they do .

来自文档:

Because most ASP.NET server control events require a round trip to the server for processing, they can affect the performance of a page. Therefore, server controls offer a limited set of events, usually only click-type events. Some server controls support change events. For example, the CheckBox Web server control raises a CheckedChanged event in server code when the user clicks the box. Some server controls support more abstract events. For example, the Calendar Web server control raises a SelectionChanged event that is a more abstract version of a click event.

当然,您可以编写自己的客户端控件,但这需要更多的工作。文章Server Event Handling in ASP.Net讨论这个。总而言之,重要的部分是实现 RaisePostBackEvent

如果您想提供多个事件,那么您可以改变从客户端发送到此方法的事件参数,并引发适当的服务器端事件。这可以像 if 语句一样简单。一个基本示例是有两个客户端 javascript 事件,每个事件都可能调用:

__doPostBack(controlId, 'superclick');

__doPostBack(pageId, 'superchange');

然后,在您的回发事件处理程序中,根据传递的参数调用所需的服务器端事件。一个简单的 RaisePostBackEvent 服务器端处理程序将如下所示:

  public void RaisePostBackEvent(string eventArgument){

     if(eventArgument == "superclick")
     {
        OnSuperClick(this, new EventArgs());
     }

     if(eventArgument == "superchange")
     {
        OnSuperChange(this, new EventArgs());
     }         

  }

关于asp.net - ASP.NET 如何知道在回发期间触发哪个事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9989122/

相关文章:

asp.net - 创建30秒的MP3文件预览

c# - ASP.NET TextBox 忽略更新面板

c# - 将 MS Access 数据库转换为 Web 应用程序的简便方法

javascript - 将 css 和 javascript 与 webforms bundle 在一起

asp.net - 在没有特定需要的情况下在 ASP.Net 页面上使用 Async ="true"可能出现的问题

c# - 更改母版页内容区域中的表单目标

html - iframe { 高度 :70%;} not working in IE 8 and Firefox

c# - 未观察到任务的异常

jquery - 添加 runat ="server"时日期选择器不工作

c# - ASP.NET 客户端验证与服务器端验证