Enrich Your Web Apps
Call a Server-Side Page Method with AJAX
October 30, 2009
Exploring ASP.NET & Web Development
Enrich Your Web Apps
Call a Server-Side Page Method with AJAX
By Don Kiely
One of the interesting things you can do with client-sideJavaScript using the ASP.NET AJAX Client Library is to call a page method fromclient code. This means that if you have an existing page with a server-sidemethod, you can call the method from client-side JavaScript. And, it is donewithout a full or partial page postback.
This may seem to be a bit counter-intuitive. Doesn tserver-side code in a Web page in ASP.NET by definition require a postback? Notat all. The way ASP.NET allows this is by turning the method into a proxy Webservice that is callable from client-side script, very much like calling aregular ASP.NET Web service.
There are just a few things you need to do differentlywhen calling a page method instead of a Web service, so here I ll focus on thedifferences. First, of course, the code behind the page needs to have a methodto call, and here I ll use GetInventory. The following code implements thatmethod, and includes the WebMethod attribute to make it callable from script.It must be a static/shared method, and you don t have to use the ScriptServiceattribute on the class. The code in the method itself is pretty typical ADO.NETcode, taking a product ID for the Northwind database and returning the numberof that product in inventory. This code is C#, but you can do the same sort ofthing in Visual Basic:
[System.Web.Services.WebMethod]
public static short GetInventory(int ProductID)
{
short retVal = 0;
string strCnn =
GetConnectionString("NorthwindConnectionString");
string strSQL = "SELECT UnitsInStock FROM Products " +
"WHERE ProductID = @ProductID";
SqlConnection cnn = new SqlConnection(strCnn);
cnn.Open();
SqlCommand cmd = new SqlCommand(strSQL, cnn);
cmd.Parameters.Add(new SqlParameter("@ProductID",
ProductID));
try
{
retVal = (short)cmd.ExecuteScalar();
}
catch (Exception e)
{
if (e.Message ==
"Object reference not set to an instance of anobject.")
throw new Exception("Invalid product ID. Please tryanother.");
else
throw;
}
finally
{
cnn.Close();
}
return retVal;
}
The ScriptManager control as used in the page that callsthe method is defined a little differently in order to invoke a page method.You don t need a Services element to identify the Web service that the scriptwill call. You do need, however, to set the EnablePageMethods attribute totrue. Below is the ScriptManager control in the page:
runat="server"EnablePageMethods="true">
The only other change is that the client-side getInventoryfunction must call the page method instead of a Web service. It does this usingthe PageMethods object, which was enabled by setting the ScriptManager s EnablePageMethodsattribute to true. (The page won t recognize the PageMethods object withoutthat attribute setting.) Otherwise, the call to GetInventory is pretty much thesame as calling any Web service:
function getInventory()
{
PageMethods.GetInventory($get("txtProductID").value,
getInventorySuccess, getInventoryFail);
}
If you ve shied away from enriching your Web applicationswith client-side JavaScript code in the past, you might find that the AJAXClient Library makes it easy enough to consider using in the future. You llneed to learn JavaScript a bit beyond the basics, because the library builds onJavaScript that might be confusing if you re only familiar with server-side.NET languages. But the possibilities for enriching the usability and value ofyour applications will almost certainly be worth it in the long run. Besides,it is likely that this is the direction we re headed in the future, enhancingthe client-side features of the Web. The server side may just become the darkside of the future!
Don Kiely, MVP,MCSD, is a senior technology consultant, building custom applications as wellas providing business and technology consulting services. His development workinvolves tools such as SQL Server, Visual Basic, C#, ASP.NET,and Microsoft Office. He writes regularly for several trade journals, andtrains developers in database and .NETtechnologies. You can reach Don at mailto:[email protected]and read his blog at http://www.sqljunkies.com/weblog/donkiely/.
About the Author
You May Also Like