Take Control - 30 Oct 2009

Gear Up with the Atlas Control Toolkit

Dan Wahlin

October 30, 2009

14 Min Read
ITPro Today logo

CoverStory

LANGUAGES: VB.NET

ASP.NETVERSIONS: 2.0

 

Take Control

Gear Up with the Atlas Control Toolkit

 

By Dan Wahlin

 

It seems that people have a general attraction tobuzzwords. Over the past few years, buzzwords like XML, Web services, and SOAs(Service Oriented Architectures) have stood atop the development buzzwordslist. However, a new player in the world of buzzwords has surfaced: AJAX(Asynchronous JavaScript and XML). AJAXoffers a lot of promise for building dynamic and interactive Web applications. Whilethe term AJAX sounds prettyfancy, it s really nothing more than a way to enable end users to interact withWeb pages quickly and easily without requiring constant postback operationsevery time a user clicks their mouse.

 

If you haven t been exposed to the term AJAX,it incorporates technologies such as JavaScript, XML, Web services, and DHTMLand uses them to make calls back to a server from within a Web page. This isaccomplished by using a special XMLHttp object that can send and receive datato and from a server without reloading the entire page. Although the term AJAXhadn t yet been coined, I first wrote about AJAXconcepts and how they could be used in Internet Explorer 5 or higher (see CreateEfficient UIs). Since then, AJAXtechnologies have been integrated into nearly every mainstream browser, whichmakes them a viable option for today s Web applications.

 

Several new frameworks are now available that allow AJAXfunctionality to be added into ASP.NET applications, including Ajax.NET (http://www.ajaxpro.info/) and Microsoft sAtlas framework (http://atlas.asp.net/). Atlasallows new and existing ASP.NET Web pages to leverage AJAXtechnologies with a minimal amount of code through the use of client-side andserver-side techniques.

 

In addition to releasing the Atlas framework to support AJAXprinciples, Microsoft has also released an Atlas Control Toolkit (http://atlas.asp.net/) that provides severaldifferent AJAX-enabled controls that developers can integrate into theirASP.NET Web applications with minimal effort. The code for all the controls isopen source and will ultimately contain controls created by both Microsoft andnon-Microsoft developers.

 

The Atlas Control Toolkit is currently in a technologypreview state, so you can expect it to change and mature over time. Although it srelatively new and still evolving, the toolkit includes several very capablecontrols that can be used today. In this article I ll discuss four controlsfrom the Atlas Control Toolkit and show how they can be used within ASP.NETapplications.

 

What s in the Atlas Control Toolkit?

The Atlas Control Toolkit is a collection of AJAX-enabledcontrols or control extenders (with source code) along with their associateddemos. To use the controls you must have the Atlas framework downloaded andenabled for a given ASP.NET Web site. Visit the Atlas Web site (http://atlas.asp.net/) for additional detailson adding Atlas functionality to a Web site, or see my earlier Atlas article, Leveragethe Web.

 

The number of controls within the toolkit is expected toincrease to 50+ as it matures and the community around it grows. Examples ofcontrols currently in the toolkit include a CascadingDropDownList control that linksmultiple dropdown list controls together and allows filtering to occur as itemsare selected, a CollapsiblePanel control that allows content to be shown orhidden, a ToggleButton control that allows checkbox states to be representedwith images, and a DragPanel control that allows content to be dragged anddropped anywhere on a page. There are several other controls that can handledisplaying watermark images in TextBoxes, rounding corners around controls,plus much more. The remainder of this article will focus on four of my favorites:the HoverMenu, ModalPopup, PopupControl, and ReorderList controls.

 

ASP.NET 2.0 includes a new Menu control that allowsdynamic menus to be displayed to end users. So why does the Atlas ControlToolkit include a HoverMenu control? While certainly you can emulate thefunctionality provided by the HoverMenu using the standard Menu control,HoverMenu simplifies hooking up menus to a variety of other controls, as wellas dynamically showing and hiding them. To better understand how the HoverMenucontrol works, Figure 1 shows how it can be used with a GridView control todynamically show and hide Edit and Delete LinkButton controls as a user hoversover a row. Figure 2 shows what the menu looks like as the user hovers over arow that is in edit mode.

 


Figure 1: The HoverMenu controlallows menus to easily be shown or hidden as end users hover over differentcontrols.

 


Figure 2: When a user hovers over aGridView row that is currently being edited they will see the Update and CancelLinkButton controls.

 

To use the HoverMenu control with the GridView control youmust first reference the AtlasControlToolkit.dll assembly available in thetoolkit download. Next you must register the assembly within the ASP.NET pageusing the Register directive:

 

<%@ Register Assembly="AtlasControlToolkit"

 Namespace="AtlasControlToolkit"TagPrefix="atlasToolkit" %>

 

Once the assembly is registered, you must add an AtlasScriptManager control into the page (the atlas prefix shown here isautomatically registered in web.config when using the VS.NET 2005 Atlas Web sitetemplate included with the Atlas framework):

 

 

The menu that will dynamically be shown and hidden mustthen be defined along with the HoverMenu control inside a TemplateField controlfor the GridView. For the example shown in Figure 1, a simple Panel with theappropriate LinkButtons inside it was placed inside a TemplateField control sItemTemplate. The HoverMenu control was then defined directly within theItemTemplate (see Figure 3).

 

 

   

    ID="PopupMenu"runat="server">

      

       

         CommandName="Edit" Text="Edit" /> 

         
 

       

         CommandName="Delete" Text="Delete" /> 

     

   

   

     

       

         

             

                runat="server"

                Text='<%#Eval("CompanyName") %>' />

         

         

             

                 Text='<%#Eval("ContactName") %>' />

         

         

            

               Text='<%#Eval("ContactTitle") %>' />

         

       

     

   

   

      

        HoverCssClass="popupHover"m

         PopupControlID="PopupMenu"PopupPosition="Left"

         TargetControlID="pnlReadOnlyData" PopDelay="25" />

   

 

Figure 3: TheHoverMenu is capable of showing and hiding different controls. This exampledefines menu items within a Panel control.

 

Looking at Figure 3 you ll see that the HoverMenu controlis referenced by using the atlasToolkit prefix defined earlier, followed by theHoverMenuExtender class name (several toolkit controls have Extender appendedto their name because they extend the functionality of existing controls). Propertiesfor the control are defined by adding an tag. This example identifies the appropriate control containing menu items toshow and hide by using the PopupControlID property. It also identifies thecontrol that should trigger the menu to be shown or hidden using theTargetControlID property. Finally, the position of the hover menu is identified(Left), as well as the amount of delay before the menu is shown or hidden asthe end user moves their mouse in and out of a given GridView row.

 

The Update and Cancel LinkButtons shown in Figure 2 aredefined in a similar manner, along with a HoverMenuExtender within theEditItemTemplate for the TemplateField control. The downloadable source codefor this article contains the complete code (see end of article for downloaddetails).

 

There may be times when you might want to pop up a custommodal dialog box when designing custom Web applications. While you cancertainly accomplish this task fairly easily on your own, the Atlas ControlToolkit supplies a ModalPopup control that can be used to show a modal dialogwindow and perform an action when the user clicks a button within it. Figure 4shows an example of using the ModalPopup control to confirm whether or not auser wants to delete a row in a GridView.

 


Figure 4: The ModalPopup control allowscustom modal dialog boxes to be displayed to end users in a cross-browsermanner (Firefox is shown here). The background of the page can be grayed out byusing simple CSS.

 

As shown in Figure 5, the ModalPopup control code wasadded into the GridView control s TemplateField to display the custom modaldialog box shown in Figure 4.

 

 

   

      Text="Delete" CommandName="Delete" />

   

      runat="server">

       

          TargetControlID="lbDelete"PopupControlID="Panel1"

          BackgroundCssClass="modalBackground"

          DropShadow="true" OkControlID="btnOK"

          OnOkScript="OKClicked()"

          CancelControlID="btnCancel" />

   

 

Figure 5: TheModalPopupExtender control can be used to display customized modal dialogboxes.

 

The ModalPopupProperties code shown in Figure 5 definesthe target control that triggers the modal dialog box to appear (lbDelete inthis case), the ID of the popup control that contains the dialog box controls(Panel1), the CSS class to apply to the page s background when the dialog boxis showing, and whether or not to add a drop shadow around the dialog box. Italso defines the OK and Cancel button IDs, as well as the JavaScript functionto call on the client side when the OK button is clicked.

 

I wasn t able to add a data binding expression within theOnOkScript property value (see Figure 5) to dynamically identify which Deletebutton triggered the dialog box. The data binding expression was output to theHTML source code rather than being evaluated on the server. As a result, Ienhanced the Delete button to write the index position of the Delete buttonwithin the GridView rows collection to a hidden field as it was clicked. As theuser clicks the OK button, the OKClicked JavaScript function is called and thehidden field is read to know which row to delete:

 

function OKClicked() {

 //Read from hidden field valueset when user clicks

 //the Delete LinkButtonto know which one they clicked.

 var id =document.getElementById('hidRowID').value;

 //Trigger a postback todelete the proper row

 __doPostBack(id,'');

}

 

The code accompanying this article contains all thedetails, so I won t describe the workaround any further. I m hoping that futureversions of the control will support dynamic data binding expressions withinthe OnOkScript property value.

 

It seems that more and more travel sites display dynamicpopup calendars in their Web pages. You click in a textbox and a calendarinstantly appears below it so that you can quickly and easily select a date. Thistechnique can be accomplished manually by using ASP.NET server controls, suchas the Calendar control, along with a little JavaScript. But with the toolkit sPopupControl, it can be done in a snap with little coding on your part.

 

Figure 6 shows an example of using the PopupControl toassociate a GridView with a TextBox so that customer IDs can be visuallyselected. The top image shows what the page looks like before the user clicksin the TextBox; the bottom image shows what the page looks like after the userclicks in the TextBox (no postback operation is performed to show the GridViewcontrol).

 


Figure 6A: The PopupControl can beused to dynamically show different controls with a minimal amount of code.

 


Figure 6B: The PopupControl can beused to dynamically show different controls with a minimal amount of code.

 

You can add a PopupControlExtender into the page to makethis type of behavior occur:

 

 "PopupControlExtender1"runat="server">

   

     TargetControlID="txtCustomerID"

     PopupControlID="pnlCustomers"

     Position="Bottom" />

 

The TextBox that causes the GridView control to be shownis identified with the TargetControlID property; the Panel control thatcontains the GridView is identified with the PopupControlID property. Theposition where the GridView should be shown in relation to the TextBox isdefined with the Position property. Position accepts values of Bottom, Center,Left, Right, and Top.

 

Because the GridView control allows paging and sorting operationsto occur that normally cause postbacks, it (and the PopupControlExtender) iswrapped with an Atlas UpdatePanel control (see Figure 7). This allows the enduser to navigate through the GridView records without posting back each timethey click on a different page number or sort column. Once the user finds theproper record and clicks the Select link, the SelectedIndexChanged event willfire on the server side and the selected customer ID value will be added intothe TextBox control. This is done by calling the PopupControlExtender control sCommit method within the event handler:

 

Protected Sub gvCustomers_SelectedIndexChanged(ByVal sender _

 As Object, ByVal e AsSystem.EventArgs) _

 HandlesgvCustomers.SelectedIndexChanged

    PopupControlExtender1.Commit(txtCustomerID,_

      gvCustomers.SelectedValue)

End Sub

 

Because the GridView control is placed within theUpdatePanel control, the server-side call to the SelectedIndexChanged eventhandler method will not cause a postback operation.

 

   

       

           

             ID="PopupControlExtender1" runat="server">

               

                 TargetControlID="txtCustomerID"

                 PopupControlID="pnlCustomers"

                 Position="Bottom" />

           

           

              AutoGenerateColumns="False" CellPadding="4"

              DataKeyNames="CustomerID"

              DataSourceID="SqlDataSource1"

              AllowPaging="True" AllowSorting="True">

    ...Column definitions omitted for brevity...

           

       

   

Figure 7: TheUpdatePanel control is part of the Atlas framework and allows existing ASP.NETcontrols, such as GridView, to leverage AJAXtechnologies. The GridView control must be placed within the UpdatePanel sContentTemplate tag.

 

Reordering Lists of Data

If you ve ever had to write code to allow users to reorderlists of data using drag and drop techniques, then you know how tricky thatprocess can be (if you haven t, then take my word for it). Fortunately, theAtlas Control Toolkit includes a ReorderList control that makes itstraightforward to perform this type of activity and do it without requiringpostbacks. There are many uses for the ReorderList control, such as rearrangingtasks, links, schedules, line items, and more. Figure 8 shows an example of howthe ReorderList control looks as an end user reorders a list of links.

 


Figure 8: The ReorderList controlallows an end user to easily reorder a list of items without requiring anypostback operations. The control generates all the necessary JavaScript code tomake this magic happen.

 

Figure 9 shows how the ReorderList control can be addedinto an ASP.NET page. Looking through the code you ll see that it containsItemTemplate, ReorderTemplate, and InsertItemTemplate templates. TheItemTemplate and InsertItemTemplate templates are similar to the templatesfound in other controls, such as GridView. The ReorderTemplate allows you todefine how the control looks as a user drags and drops items in the list. Inthis example, the ReorderTemplate specifies a CSS class named reorderCue thatshould be used to draw a dotted border around the item being moved (refer backto Figure 7 to see the effect of the CSS).

 

 DataSourceID="sdsLinks" DataKeyField="ID"

 SortOrderField="Position" AllowReorder="True"

 ShowInsertItem="True">

  

    

        

          Text='<%#Eval("Title") %>'>

        

          Text='<%#Eval("Link"," ({0})") %>'>

    

  

  

    

    

  

  

    

  

  

    

      thin solid transparent;">

        Title:

        

           Text='<%#Bind("Title") %>'>

        

        Link:

        

           Text='<%#Bind("Link") %>'>

        

           CommandName="Insert">Add

    

  

Figure 9: TheReorderList control provides several different templates that allow you tocontrol how the list of items is displayed. This example binds the ReorderListcontrol to a SqlDataSource control to retrieve data from a SQL Server 2005Express database.

 

When I first began using the ReorderList I didn t realizethat it would automatically update the position of each item in the database asthe items were reordered. You, of course, must add some type of position fieldto the database table for this to happen. I added a simple integer field namedPosition, then proceeded to write all the code to handle updates to the fieldas items were moved up or down in the list. It turns out that the ReorderListcontrol handles all that automatically because it tracks the previous and newposition of any item that is dragged to a different position in the list. Iwasn t happy with myself for not researching that fact first, before writingcode, but it was a good exercise (at least that s what I m telling myself). Thesample code included with the article contains the original code I wrote. It snot advanced, by any means but it should give you an appreciation for thework that the control does for you.

In addition to allowing templates to be defined, theReorderList control can also be bound directly to data source controls, such asSqlDataSource or ObjectDataSource. In this example I bound it to aSqlDataSource control (mainly to keep things simple). As items are reordered byan end user, the control knows how to update the proper database fields becausethe column names to use are identified by the DataKeyField and SortOrderFieldproperties. I gave the SortOrderField a value of Position because that was thename of the field that tracked each item s position in the database.

 

If you choose to leverage the control s built-in characteristicsyou don t have to write any additional code to get it working. Otherwise, thecontrol exposes an ItemReorder event that allows you to interact with each dragand drop operation on the server side.

 

Conclusion

I ve only scratched the surface of what the Atlas ControlToolkit has to offer. The toolkit is still relatively young; it will certainlygrow and mature over time. Expect new controls to be added and existingcontrols to be enhanced.

 

Although still young, the current offering provides severalcontrols that make it relatively straightforward to perform common tasks, suchas popping up controls dynamically, showing modal dialog boxes, and reorderinglists. Combining the capabilities of the Atlas framework with the toolkitcontrols provides developers with a rich AJAX-enabled development environmentthat can lead to an enhanced user experience.

 

The sample code referencedin this article is available for download.

 

Dan Wahlin(Microsoft Most Valuable Professional for ASP.NET and XML Web services) is thepresident of Wahlin Consulting, as well as a .NET development instructor atInterface Technical Training. Dan founded the XML for ASP.NET Developers Website (http://www.xmlforasp.net/), whichfocuses on using XML, ADO.NET, and Web services in Microsoft s .NET platform.He s also on the INETA Speaker s Bureau and speaks at several conferences. Danco-authored Professional Windows DNA(Wrox), ASP.NET: Tips, Tutorials, and Code(SAMS), ASP.NET 1.1 Insider Solutions (SAMS),and ASP.NET 2.0 MVP Hacks (Wrox), andauthored XML for ASP.NET Developers (SAMS).When he s not writing code, articles, or books, Dan enjoys writing andrecording music and playing golf and basketball.

 

 

 

Read more about:

Microsoft
Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like