Wednesday, March 28, 2012

Page_Load and ajax

I have a simple question. when I use an UpdatePanel control, it is not supposed to refresh the page entirely, only a part of the page.

But why it calls Page_Load event ?

Here's the example used :

<!-- <Snippet2> -->
< Page Language="C#" %
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
protected void Search_Click(object sender, EventArgs e)
SqlDataSource1.SelectParameters["SearchTerm"].DefaultValue =
Label1.Text = "Searching for '" +
Server.HtmlEncode(SearchField.Text) + "'";

protected void ExampleProductSearch_Click(object sender, EventArgs e)
SqlDataSource1.SelectParameters["SearchTerm"].DefaultValue =
Label1.Text = "Searching for '" +
Server.HtmlEncode(ExampleProductSearch.Text) + "'";
SearchField.Text = ExampleProductSearch.Text;
<html xmlns="">
<head id="Head1" runat="server">
<title>UpdatePanel Trigger Example</title>
<style type="text/css">
body {
font-family: Lucida Sans Unicode;
font-size: 10pt;
button {
font-family: tahoma;
font-size: 8pt;
<form id="form1" runat="server"
defaultbutton="SearchButton" defaultfocus="SearchField">
<asp:ScriptManager ID="ScriptManager1" runat="server" />

Search for products in the Northwind database. For example,
find products with
<asp:LinkButton ID="ExampleProductSearch" Text="Louisiana" runat="server" OnClick="ExampleProductSearch_Click">
</asp:LinkButton> in the title. <br /><br />
<asp:TextBox ID="SearchField" runat="server"></asp:TextBox>
<asp:Button ID="SearchButton" Text="Submit" OnClick="Search_Click"
runat="server" />

<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional"
<asp:AsyncPostBackTrigger ControlID="SearchButton" />

<asp:Label ID="Label1" runat="server"/>
<br />
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" DataSourceID="SqlDataSource1">
No results to display.
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="Data Source=.\SQLEXPRESS;AttachDbFilename='H:\Program Files\Microsoft ASP.NET\ASP.NET AJAX Sample Applications\v1.0.61025\Contacts\App_Data\Contacts.mdf';Integrated Security=True;User Instance=True"
SelectCommand="SELECT [Location] FROM
Contacts WHERE ([FirstName] LIKE
'%' + + '%')">
<asp:Parameter Name="SearchTerm" Type="String" />


<!-- </Snippet2> -->

Here's some background info: (see third section on How UpdatePanel's Work)

Basically, during an async postback, the full server page life cycle is executed to the point of rendering similar to a "regular" postback. At the render phase for an async postback the framework determines that only the content of UpdatePanels need to be refreshed.

If you want to not run code during an async postback, use the ScriptManager.IsInAsyncPostBack to check if you are in async postback and then take action.

No comments:

Post a Comment