Sunday, January 25, 2009

Making sure you don't process page_load code when doing ajax

When you perform an async call using ajax, you will cause page_load to fire.
There are two ways around this I use.

During ajax, we are having a postback, so Page.IsPostBack is true, and also ScriptManager.IsInAsyncPostBack is true as well. These two items generally point to ajax.
if (!Page.IsPostBack && !ScriptManager.IsInAsyncPostBack)


If you want to be certain - then you can name your controls with a particular prefix, for example "ajax" so a button could be ajaxLoadDynamicData.

In your Page_Load:

Control ctl = PostBackInformation.GetPostBackControl(this.Page);
if ((ctl != null) && (ctl.ID.IndexOf("ajax", 0, StringComparison.InvariantCultureIgnoreCase) > -1))
{
return;
}

PostBackInformation.GetPostBackControl is not built in - I don't recall where I got it or customized it from (there are several references to it on the net)


public static System.Web.UI.Control GetPostBackControl(System.Web.UI.Page page)
{
Control control = null;
string ctrlName = page.Request.Params["__EVENTTARGET"];
if (ctrlName != null && ctrlName != String.Empty)
{
control = page.FindControl(ctrlName);
}
// if __EVENTTARGET is null, the control is a button type and we need to
// iterate over the form collection to find it
else
{
string ctrlStr = String.Empty;
Control c = null;
foreach (string ctl in page.Request.Form)
{
// handle ImageButton controls ...
if (ctl.EndsWith(".x") ctl.EndsWith(".y"))
{
ctrlStr = ctl.Substring(0, ctl.Length - 2);
c = page.FindControl(ctrlStr);
}
else
{
c = page.FindControl(ctl);
}
if (c is System.Web.UI.WebControls.Button
c is System.Web.UI.WebControls.ImageButton)
{
control = c;
break;
}
}
}
return control;
}


so depending on your scenario you can detect when doing a postback from an ajax (or any) control and ignore processing.

No comments:

Post a Comment