I didn't want to create an ASP.NET Ajax extender for such a simple task, but after a few hours of Google-ing, I found a few nice articles on Ben Rush's blog, which is a very valuable source of knowledge on the internals of ASP.NET Ajax, ScriptManager and other ASP.NET Ajax goodies.
- How UpdatePanel works
- How UpdatePanel works, part II
__doPostBack('<%= Button_Search.ClientID %>','');
Yes, that easy. Nice, isn't?
But in my page I also had to pass a value to the UpdatePanel, so the button was not enough.
So I adapted a bit Ben's solution, and I add hidden text box, and update its value before calling the doPostBack method.
To implement that you need to add 4 "things" in your ASP.NET web form.
Add the hidden textbox
You need a textbox to store the value you want to pass over to the UpdatePanel, but you don't want to show it in the page, so it must be hidden via CSS.
<asp:TextBox ID="text" runat="server" style="display:none;"></asp:TextBox> <asp:Button ID="button" runat="server" OnClick="button_Click" style="display:none;"/>
Register the async trigger for the UpdatePanel
<asp:UpdatePanel runat="server" ID="UpdatePanel1" UpdateMode="Conditional"> <ContentTemplate> <asp:Label ID="label" runat="server"></asp:Label> </ContentTemplate> <Triggers> <asp:AsyncPostBackTrigger ControlID="button" EventName="Click" /> </Triggers> </asp:UpdatePanel>
You see that I registered an AsyncPostBackTrigger on the Click event of the button.
I also added a label that will be updated by the event raised by the textbox. Remember to set the UpdateMode to Conditional, otherwise the UpdatePanel will always be refreshed, not only when there is a postback inside or when a trigger fires.
var obj = document.getElementById("<%= text.ClientID %>");
__doPostBack("<%= button.ClientID %>","");
Using the ClientID property of the control will ensure that you get the right ID even if the control is inside a masterpage, a webcontrol, a repeater or whatever might change the ID.
I set the value on the hidden textbox but I do the postback on the button.
Update the contents of the UpdatePanel
protected void button_Click(object sender, EventArgs e)
label.Text = text.Text;
This changes the text in the label inside the UpdatePanel with the value set in the hidden textbox and passed through by the async postback.
Here is a file with a working sample: UpdatePanelAndJS.aspx