Morvael Morvael - 1 month ago 12
Ajax Question

ASPX Page Life Cycle when calling [WebMethod]s

I'm calling a number of methods that have been decorated with [WebMethod] via jQuery ajax.

These require a database connection to be set up in an external library that will be the same for each method.

My original code looked like this:

public partial class Server : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// code to set up DB connections
ExternalLibrary.SetupDB();
}

[WebMethod]
public static string AjaxAccessibleMethod()
{
try
{
// get some data from the database via the external library
ExternalLibrary.CallDatabase();
}
catch(Exception ex)
{
// handle errors
}
}
}


This was working, but then started throwing exceptions claiming that the ExternalLibrary's database hadn't been initialized.

Placing breakpoints in my code I found that the Page_Load event wasn't being called when calling my AjaxAccessibleMethod, I also tried moving the DB setup stuff into the Page_Init event but likewise that wasn't called.

Can anyone explain to me the aspx page life cycle when using WebMethods? The fact that this worked initially seems to imply that Page_Load was called, but it no longer is.

Answer

Notice that the method you are using as WebMethod is static, this should be the first hint to the fact that Page object is not created at all.

Page Methods is a simple alternative to full blown web services, and as such, its life cycle is more similar to web service than to page. That is, request goes through the general ASP.NET pipeline, with objects like HttpContext, Request and such. But then the difference happens: for page requests and postbacks page object is created and the whole series of page events happens, whereas for page methods page object is not created, and method is simply called as Server.AjaxAccessibleMethod().

There is really no way to mix the two, because this would unnecessarily complicate processing of calls to page methods. So the only path forward for you here is duplicate necessary code:

protected void Page_Load(object sender, EventArgs e)
{
    // code to set up DB connections
    ExternalLibrary.SetupDB(); 
}

[WebMethod]
public static string AjaxAccessibleMethod()
{
    ExternalLibrary.SetupDB();
    ...
}
Comments