1

有时我在使用 ASP.Net 时会感到绝望——另一个不应该的问题!

在 Web 表单上有一个 ASP 表。在 ASP 表中有一个用户控件,我正在对其进行一些更改。在 ASP 表中有一个文本框....到目前为止没有任何异常!

在后面的代码中,作为 Page_Load 的一部分,我需要访问文本框的 ClientID 以注册一些 javascript ......所以我这样做了,而且 javascript 似乎做了它需要做的一切。每个人都很高兴。

不,不,显然每个人都不高兴,ASP.Net 本身就很不高兴!

在访问 ClientID 时,源中出现的 id 是:

myControl_myTextBox

注释掉访问 ClientID 的行意味着 id 呈现为:

ctl00_BodyPlaceHolder_myControl_myTextBox

访问 ClientID 的行如下所示:

jsBuilder.AppendFormat(@"var filter = new TBFilter($(""#{0}"")[0]);", myTextBox.ClientID);

这本身并不困扰我,但它打破了回发的事实,确实如此!如果您在该文本框中输入内容并点击提交按钮(页面上有一个提交按钮!),它会重新加载页面,但会将默认值放回文本框中并完全忽略您最初拥有的内容。疯狂 - 我没有做任何特别奇怪和不寻常的事情,那么为什么它会破坏回发呢?

4

1 回答 1

3

The javascript you register in page load, does that do something that should not happen in a postback? If so, you should check on the Page.IsPostback to control when to use it.

You should also be aware that in the page life cycle, Page_Load occurs before any control postback events (which is for instance Click event on button). So if the javascript code you register depends on result from the Click event, you should either register it inside the Click event (if it should only happen when clicked on that button), or the Page_PreRender event (if it should always happen).

EDIT:
It also might be that some changes are made after Page_Load to how the client id's are created. It may be best to do it in the Page_PreRender event to make sure everything is finished loading.

于 2009-09-10T09:38:21.673 回答