事件处理程序和回传(.NET) [英] eventhandler and postback (.net)

查看:113
本文介绍了事件处理程序和回传(.NET)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的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应该这样做,这不是它的。为了澄清,为说明<一href="http://msdn.microsoft.com/en-us/library/system.web.configuration.pagessection.autoeventwireup.aspx"相对=nofollow> 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);
}

这篇关于事件处理程序和回传(.NET)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆