不能让我的事件触发 [英] Can't get my event to fire

查看:103
本文介绍了不能让我的事件触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在加载页面的第一次(!的IsPostBack),我创造了code按钮并将其添加到我的网页,然后添加一个事件处理程序的Click事件。

When loading a page for the first time (!IsPostback), I am creating a button in code and adding it to my page, then adding an event handler to the click event.

但是,单击该按钮时,页面重新加载后,我的事件处理程序不火。

However, when clicking the button, after the page reloads, my event handler does not fire.

任何人能解释为什么吗?

Can anyone explain why?

推荐答案

布拉德:你的回答是不完整的;他是最有可能做的页面生命周期为时已晚,在Page_Load事件中。

@Brad: Your answer isn't complete; he's most likely doing it too late in the page lifecycle, during the Page_Load event.

好吧,这里是你错过了什么。

Okay, here's what you're missing.

ASP.NET是无状态的。这意味着,你的网页渲染和发送到浏览器,页面对象,一切都在它被摧毁后。没有链接,保持该网页的服务器上,什么是对用户的浏览器。

ASP.NET is stateless. That means, after your page is rendered and sent to the browser, the page object and everything on it is destroyed. There is no link that remains on the server between that page and what is on the user's browser.

当用户点击一个按钮时,发送该事件回服务器,以及其他信息,如隐视图状态字段。

When the user clicks a button, that event is sent back to the server, along with other information, like the hidden viewstate field.

在服务器端,ASP.NET确定哪些页处理请求,并从头重建页。服务器控件的新实例被创建,并根据.aspx页面中链接到一起。一旦被重新组装时,回发数据进行评价。视图状态是用来填充的控制和事件被解雇。

On the server side, ASP.NET determines what page handles the request, and rebuilds the page from scratch. New instances of server controls are created and linked together according to the .aspx page. Once it is reassembled, the postback data is evaluated. The viewstate is used to populate controls, and events are fired.

这一切都发生在一个特定的顺序,叫做页面生命周期的。为了做到在ASP.NET更复杂的事情,如创建动态控件并在运行时将其添加到网页,您必须了解页面生命周期。

This all happens in a specific order, called the Page Lifecycle. In order to do more complex things in ASP.NET, such as creating dynamic controls and adding them to the web page at runtime, you MUST understand the page lifecycle.

通过您的问题,你必须创建一个按钮,每一次网页加载。此外,必须在前面的事件在页面上发射创建按钮。控制事件的Page_Load和Page_LoadComplete之间开火。

With your issue, you must create that button every single time that page loads. In addition, you must create that button BEFORE events are fired on the page. Control events fire between Page_Load and Page_LoadComplete.

您想您的加载ViewState的控制信息进行解析,并添加到控件之前,而之前控制事件触发,所以你需要处理preINIT事件,在这一点上添加按钮。同样,你必须这样做,每次页面加载。

You want your controls loaded before ViewState information is parsed and added to controls, and before control events fire, so you need to handle the PreInit event and add your button at that point. Again, you must do this EVERY TIME the page is loaded.

最后一点;网页事件处理是ASP.NET有点奇怪,因为事件自动装配起来。注意Load事件处理程序被调用的Page_Load ...

One last note; page event handling is a bit odd in ASP.NET because the events are autowired up. Note the Load event handler is called Page_Load...

这篇关于不能让我的事件触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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