In my latest job, I've been doing a lot of work with Microsoft and ASP.Net. I've recently started using the AJAX library for ASP.Net 2.0 and, while it has gone surprising well for the most part, there was one problem in general I couldn't find an answer for online so I thought I'd post my solution.
Working with a GridView in an Update Panel is pretty quick and simple for many reasons, but when you require a full postback instead of an asynchronous one you can run into some trouble. If the actual object to cause the full postback has a set ID
, no problem simply add:
<asp:UpdatePanel ...>
<ContentTemplate>...</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="CONTROL_ID" />
</Triggers>
</asp:UpdatePanel>
The PostBackTrigger defined there will issue a full page postback. The problem arises on run-time controls such as a TemplateField
or ButtonField
within the GridView. There is no (easy) way to assign them as PostBackTrigger as either you don't know the ID (in a ButtonField
example) or the ID changes based on any MasterPages or panels. The solution is simple though.
Basically all we have to do is add the control to the Trigger collection in the code behind on the DataBind
event of the item. This will work with any type of control you want to put in your GridView. In this example, I'll use a LinkButton
in a TemplateField
.
... UpdatePanel definition etc. ...
<asp:GridView ...>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton CommandName="Select" ID="PostBackButton" runat="Server" Text="Do PostBack" OnDataBinding="PostBackBind_DataBinding">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
... Any other Columns ...
</Columns>
</asp:GridView>
Then in the codebehind:
protected void PostBackBind_DataBinding(object sender, EventArgs e)
{
LinkButton lb = (LinkButton) sender;
ScriptManager sm = (ScriptManager)Page.Master.FindControl("SM_ID");
sm.RegisterPostBackControl(lb);
}
The script manager has a handy RegisterPostBackControl
method and the link buttons are dynamically set as full postback calls.
Note: If you aren't using a Master Page, you can just get the scriptmanager via its local reference: this.SM_ID.RegisterPostBackControl(lb);
Hope this helps someone out!