System i Developers and .NET 2.0, Part 2: Web Development Using ASP.NET AJAX
November 28, 2007 Michael Sansoterra
Note: The code accompanying this article is available for download here.
In System i Developers and .NET 2.0: ASP.NET and the Declarative Programming Model, which is Part 1 of this series, I did a jet tour of the basics of .NET 2.0 and tried to present compelling reasons why System i programmers might want to learn it. Among the listed reasons to learn .NET are popularity (with a large supporting community), versatility and the ability to integrate with the AS/400 and System i world. Part 1 also presented a step-by-step scenario on how to create a basic ASP.NET Web page that can be used to maintain the data in an IBM DB2 for i5/OS table or view.
If you followed the example in Part 1, you know how to build an ASP.NET Web page designed to edit data in a database table. While the article was long, note that once you learn how to do it, it should take less than 20 minutes to generate a similar page. If you were frustrated with the article length, remember you didn’t learn IBM subfile programming in a day either! Anyway, the sample Web project is available at this link and it will serve as the basis for the sample in Part 2.
As a Quick Review
Today’s Lesson: AJAX
Question: What typically happens on an old shopping cart Web page when the quantity of an item is changed?
Answer: The whole page refreshes. This quirk about Web applications has always irritated me. Every time something small happens that requires communication to the Web server, such as changing a quantity in the shopping cart so that the price, tax, or shipping can be recalculated, the page goes blank and then reloads. And for guys who are still on dial-up, the problem is even worse!
So, in the past Web apps were clumsy at best. In my mind, they never held a candle to a true GUI application written in Windows or Java. At long last the Web development world has finally matured with the likes of Cascading Stylesheets (CSS), XHTML, and AJAX. With these tools, it is possible to build a Web page that has a similar look and feel to a true graphical application. AJAX is the technology that allows the browser to communicate with the server to fetch only the necessary pieces of data that need to be updated. In our shopping cart example, if we change the quantity of a line item, we may only need to retrieve the new extended amount, which may include tax, shipping charges and order total, but not refresh the whole page.
Since ASP.NET AJAX Extension 1.0 wasn’t released until 2007, it is not a part of the base .NET 2.0 framework. It must be downloaded here and installed on your development machine (and Web server if you plan to deploy an ASP.NET AJAX application for your user community). Future releases of ASP.NET will have the extensions built-in and hence will not require a separate download.
Once installed, start your version of Visual Studio. At this point you have two options. The first is to create a brand new AJAX enabled Website (choose File→New Project and then choose ASP.NET AJAX enabled Website from the installed templates).
The other option is to upgrade an existing Web application. For brevity’s sake, this article will take the approach of upgrading an existing Web app. In fact, we’re simply going to update the simple single-page application developed in Part 1 of this series. Click here to download the entire project. Keep in mind, you can apply these techniques to other existing pages you have. In Visual Studio, choose the option to open an existing Website and, when prompted for the source, point it to the folder location where the downloaded code was placed.
Figure 1 shows a picture of the Web page (named Default.aspx) built to maintain all entries in the department table using a special tabular control called the GridView control. Recall the main aesthetic problem with this Web page is that every time we click a button the entire page refreshes.
Download and open the sample project from the last article (or your own existing project) in Visual Studio. For this article, I’ll be using the free Visual Web Developer 2005 Express Edition. (See Part 1 for information on the various Visual Studio editions, references to the various windows in the IDE, etc.) Open the Default.aspx page for visual editing (not source editing). Review the toolbar, and you will notice a new group of tools present: the AJAX Extensions controls. Here is a description of a few of the important new AJAX controls:
Working Through the Example
Open the Default.aspx in the graphical design view. Every ASP.NET AJAX page needs a ScriptManager control, so begin by dragging the ScriptManager control from the toolbar and dropping it at the very top of the Default.aspx Web page. The ScriptManager control must be defined before any other AJAX controls appear on the page. When you drop the control, it may take a while the first time this is done because VS is updating your project to use the new AJAX libraries. This new control by default will be assigned a control ID of ScriptManager1.
Next, we need to put an UpdatePanel on the page. Any portion of the Web page placed inside an update panel can be independently refreshed without reloading the entire page. In our sample, our Default.aspx page consists primarily of a GridView control that displays existing departments. Therefore, we are going to embed our GridView control inside an UpdatePanel control. When an action occurs on the GridView, such as sorting or updating a row, the entire GridView control will be reloaded via AJAX instead of a browser page refresh.
The one drawback to this scenario is that the majority of our page will be reloaded every time the GridView control changes so we will not be getting the AJAX advantage of lighter traffic and lower bandwidth in this case. To understand the problem, consider when we’re simply change the data on one row of the GridView the whole control’s HTML output will reload via AJAX. This is theoretically unnecessary when you update one row; in this case it would be nice to just update the HTML for the one row. Oh well, that’s the penalty for using the feature-rich, “new developer friendly” GridView control. Incidentally, there are third-party grid controls that are sophisticated enough to update a single row of the grid using AJAX rather than reloading the entire grid.
As far as placing the control on the page, in my opinion it is easier to add an UpdatePanel to an existing Web page via source code rather than using the drag-and-drop operation in the visual editor. So, put the Default.aspx page in source mode and find the opening tag for the GridView control. It should look like this:
<asp:GridView ID="GridView1" … >
Rather than scanning the code, you can also use “Control+F” to activate the Find dialog window to locate text. Before this line in your source code, insert the following lines to define the UpdatePanel control called UpdatePanel1:
<asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate>
The ContentTemplate tag informs ASP.NET what text, controls, etc., will be included in the partial page refresh. Finally, locate the ending tag for the GridView control:
Insert two new lines and add the following closing tag to mark the completion of the ContentTemplate and UpdatePanel:
If you’re not literally following along in our example, generally speaking you will want to put related controls that should be refreshed together on a page within the ContentTemplate and UpdatePanel control tags. Above we sandwiched the existing GridView within the UpdatePanel and ContentTemplate tags. Just for the record, when it comes to simple pages I usually get my page working in plain old ASP.NET and add the AJAX stuff later. At this point updates to the DataGrid will be done as a partial page AJAX update instead of reloading the whole page.
Before testing this AJAX enabled page we need to manually make a change to the Web.Config file. Web.Config is an XML file that contains parameters for controlling how the Website operates. It holds various information such as database connection strings, and references to additional .NET assemblies. Locate Web.Config in the Solution Explorer window and double click to open it. Find the following closing tag:
Insert a line and paste the following XML in (pasting this exact code will only work for AJAX extensions version 1.0):
<httpHandlers> <remove verb="*" path="*.asmx"/> <add verb="*" path="*.asmx" validate="false" type= "System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/> <add verb=""*" path="*_AppService.axd" validate="false" type= "System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/> <add verb="GET,HEAD" path="ScriptResource.axd" type= "System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/> </httpHandlers> <httpModules> <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/> </httpModules>
These additional configuration settings let ASP.NET know what to do with the AJAX requests it will encounter in the project. You only need to do this step when updating an existing project. When creating a new AJAX project you won’t need to do this step because Visual Studio will add it for you automatically.
Now we only have one more little task to do. With a long-running AJAX process, it is sometimes necessary to let the users know that something is happening in the background so they don’t get fidgety and start clicking buttons unnecessarily. We can do this by adding an UpdateProgress control to our Default.aspx page. Make sure your project is not running in debug mode and, if it isn’t already, put Default.aspx into source edit mode and locate the closing tag of the ScriptManager control:
Insert a new line right after the end of the tag and insert the following lines:
<asp:UpdateProgress ID="UpdateProgress1" runat="server" DisplayAfter="0"> <ProgressTemplate> <div id="Progress" style="position:absolute; height:200px; width:40%; margin: 20% 30% 20% 30%; z-index:100; background-color:#008AC6; font-size:3em; "> Please wait while processing... </div> </ProgressTemplate> </asp:UpdateProgress>
If you downloaded the sample code to follow along, while in the Web.Config you will also need to update the connection string with your ODBC DSN name and credentials. (Search Web.Config for the text DB2Data to find the ODBC connection string.)
Now run the code again by pressing F5. This time, when you do an update to the page you will see a “Please wait while processing…” message. The duration of the message is dependent on how fast your machine is.
Well, that was easy. We can now edit data, sort our grid, and perform many other tasks without refreshing the page. Of course to polish the page there are a few additional things that could be done:
The source code for this completed AJAX enabled app can be downloaded here. If you want to try it, don’t forget to open the Web.config file and change the connection string information.
An Additional Bag of Goodies
There is another aspect of ASP.NET AJAX I need to mention. An optional companion to ASP.NET AJAX extensions is the ASP.NET AJAX control toolkit. This control toolkit is extremely powerful, offering several controls to make life as a developer a “walk in the park.” Ultimately, the aim of these controls is to give users the best possible experience using a browser application. This is one of the chief elements of the Web 2.0 phenomenon, where browser applications function almost indistinguishably from a genuine GUI program.
You can download the control toolkit here. You will see two downloads listed on the page: one with source code and one without. Download the version with the source so you can review the samples. Follow these instructions to setup an ASP.NET AJAX Visual Studio project to show these AJAX enabled toolkit controls on the toolbar. You can even see a live demo of these controls by clicking here. The left pane of the sample Web page has a list of all the controls in the toolkit. You can click on the name of each control to see how it works in a Web page and evaluate whether you have a need for it.
A few of the simple controls in the toolkit I like are:
The Road to Easy Street
Michael Sansoterra is a programmer/analyst for i3 Business Solutions, an IT services firm based in Grand Rapids, Michigan. You can contact him through our contact page.