views:

156

answers:

1

Sometimes I do despair when working with ASP.Net - another problem that shouldn't be!

On the web form there is an ASP table. In the ASP table there is a user control which I am making some changes to. In the ASP table there is a text box....nothing out of the ordinary so far!

In the code behind, as part of the Page_Load, I need to access the ClientID of the textbox in order to register some javascript...so I do and the javascript seems to do everything it needs to. Everyone's happy.

No, no apparently everyone's not happy, ASP.Net itself is very unhappy!

On accessing the ClientID, the id that appears in the source is:

myControl_myTextBox

commenting out the line that accesses the ClientID means the id is rendered as:

ctl00_BodyPlaceHolder_myControl_myTextBox

The line that accesses the ClientID looks like this:

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

This in itself does not bother me, but the fact that it breaks the postback, does! If you type something into that textbox and hit the submit button (there's a submit button on the page!), it reloads the page, but puts the default value back in the textbox and completely ignores what you originally had. Madness - I haven't done anything particularly weird and out of the ordinary, so why has it broken the postback?

+2  A: 

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.

awe
I have moved it into Page_PreRender and this seems to solve the problem. Still don't think it should have been a problem in the first place!
Paul