Welcome to WebmasterWorld Guest from

Forum Moderators: ocean10000

Message Too Old, No Replies

AJAX, User Controls and Postback

How to fire a postback from a control within a user control via JavaScript

10:01 am on Jan 22, 2009 (gmt 0)

Full Member

10+ Year Member

joined:June 29, 2005
votes: 0

Hey guys,

I'm sure this will be a 2 second fix...so here goes.

Basically, I have a user control. Inside this user control, I have a control (such as a textbox, but could be anything). This control is an asp.net control, so has an ID.

My plan is to fire a postback via javascript on an event.

I'm having to do this because I want to fire a postback on every key press in a textbox, and the OnTextChanged event only fires when the focus leaves the textbox or when the 'return' is pressed

I've set the control (within the user control) as follows -

<asp:TextBox ID="tb" onkeypress="return captureKeys(event)" runat="server" OnTextChanged="tb_TextChanged"></asp:TextBox>

And the JavaScript to handle the event when each key is pressed is as follows -

function captureKeys (evt) { ... }

My problem is this: How to I call the javascipt

event on the control? What ID to I reference? Will it be, in this example,

Cheers guys - any help would be appreciated!


11:32 am on Jan 22, 2009 (gmt 0)

Full Member

10+ Year Member

joined:June 29, 2005
posts: 216
votes: 0


So...solution found.

Take, for example, a textbox within a user control with an 'OnTextChanged' event -

<asp:TextBox ID="tb" runat="server" OnTextChanged="tb_TextChanged"></asp:TextBox>

It's all to do with the server-side method


This takes two parameters, the name of the server-side control (the ID of the control within the user control, eg, "tb" in the above example) and something else that can be an empty string.

This creates a javascript method call that forces a postback. I use it as follows on the page (user control) load -

tb.Attributes.Add("onkeyup", Page.ClientScript.GetPostBackEventReference(tb, ""));

This means that on the 'onkeyup' event of the textbox, a postback will be triggered.

Alongside this, I have implemented an AJAX UpdatePanel, with a trigger -

<asp:AsyncPostBackTrigger ControlID="tb" EventName="TextChanged" />

This will mean the entire page isn't refreshed, only the panel, allowing the user to continue typing.

Hope this helps!