事件处理程序和回发 (.net)
我有一个带有按钮的简单 asp.net 页面。
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" MasterPageFile="~/MasterPage.master"%>
<asp:Content runat="server" ID="content" ContentPlaceHolderID="ContentPlaceHolder1">
<asp:Button runat="server" ID="btn1" Text="Click me" />
</asp:Content>
使用代码:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
btn1.Click += new EventHandler(Btn1_Click);
}
}
protected void Btn1_Click(Object sender, EventArgs e)
{
//do stuff
}
当我单击按钮时,不会引发 Click 事件,但如果我将事件放入按钮的标记中,或者如果我将 EventHandler 与回发绑定,则会引发 Click 事件。为什么?我还是不明白。该事件是否不应独立于其来源而引发?
I have a simple asp.net-Page with a button.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" MasterPageFile="~/MasterPage.master"%>
<asp:Content runat="server" ID="content" ContentPlaceHolderID="ContentPlaceHolder1">
<asp:Button runat="server" ID="btn1" Text="Click me" />
</asp:Content>
with Code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
btn1.Click += new EventHandler(Btn1_Click);
}
}
protected void Btn1_Click(Object sender, EventArgs e)
{
//do stuff
}
The Click event is not raised when I click the button, but it is if I put the event in markup of button OR if I bind the EventHandler with postbacks. Why? I still don´t get it. Should the event not be raised independently of its source?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不是 100% 确定这就是您要问的,但是:如果您没有在每次加载页面时连接事件处理程序,它将不会运行。如果您认为 AutoEventWireUp 应该这样做,那不是它的用途。为了澄清这一点,AutoEventWireup 的说明说
它要么需要在控件本身上声明:
要么需要删除!Page.IsPostback,并在每次加载时绑定事件处理程序。
I'm not 100% sure this is what you're asking, but: If you're not wiring up the Event Handler every time the page is loaded, it won't run. If you think AutoEventWireUp should be doing it, that's not what it's for. To clarify, the description for AutoEventWireup says
It either needs to be declared on the control itself:
Or you need to remove the!Page.IsPostback, and bind the event handler on each load.