事件处理程序和回传(.NET)回传、事件、程序、NET

2023-09-06 19:05:00 作者:彼岸时光ど

我有一个简单的asp.net页有一个按钮。

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>

与code:

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
}

当我点击按钮的Click事件不会引发,但如果我把事件的按钮标记或者如果我绑定回发的事件处理程序。为什么?我还是鸵鸟政策得到它。如果事件不能独立的来源提出?

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?

推荐答案

我不是100%肯定这是你在问什么,而是:如果你不是每次布线事件处理程序的页面加载,它不会运行。如果您认为AutoEventWireUp应该这样做,这不是它的。为了澄清,为说明 AutoEventWireup 说:

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

自动绑定仅供页面事件进行的,而不是事件   在页面上的控制。

'Automatic binding is performed only for page events, not for events for controls on the page."

这或者需要在控制自身声明:

It either needs to be declared on the control itself:

<asp:Button runat="server" ID="btn1" Text="Click me" OnClick="Btn1_Click" />

或者你需要删除!Page.IsPostback,并绑定在每次加载事件处理程序。

Or you need to remove the!Page.IsPostback, and bind the event handler on each load.

protected void Page_Load(object sender, EventArgs e)
{
    btn1.Click += new EventHandler(Btn1_Click);
}