Centre for Software Practice

the blog
Welcome to Centre for Software Practice Sign in | Join | Help
in Search

Adam's Blog

  • AJAX in ASP.NET 2.0 - Introduction To The Basics

    This is a copy of the post on my blog Noiz Waves.

    AJAX has become quite the buzzword lately when it comes to Web 2.0. Luckily, AJAX is really easy to integrate into new and existing ASP.NET application; it's just a matter of adding some simple controls here and there. The best thing about AJAX in ASP.NET is that no complex coding is required; all the postbacks and Javascript is abstracted away.

    In this article I want to provide a quick introduction to AJAX in ASP.NET, highlighting core ideas and useful hints, aimed for existing developers who want to dabble with AJAX. I'm going to start with installing ASP.NET AJAX and configuring Visual Studio 2005 (which takes no time at all). Then its onto a description of 3 of the main controls that utilise AJAX; the ScriptManager, UpdatePanel and Timer. Finally, I will create a small project that combines these controls to perform a simple task.

    Installing ASP.NET AJAX

    Firstly, you need to have Visual Studio 2005 and .NET 2.0 installed on your machine. Once you have done this, you need to download the ASP.NET AJAX Extensions 1.0 (version correct at time of writing). The download is only a couple of megabytes and provides the essentials for AJAX'ing your websites. Whilst here, you can also download the ASP.NET AJAX Control Toolkit. It provides a large number of AJAX'ed controls which are ready to use.

    Once the extensions have been installed, all that needs doing is adding the AJAX extensions to the Visual Studio toolbox. I added the controls to a new tab called 'AJAX Extensions' by right-clicking on the tab selecting Choose Items and browsing to "C:\Program Files\Microsoft ASP.NET\ASP.NET 2.0 AJAX Extensions\v1.0.61025\System.Web.Extensions.dll" then clicking OK. If all goes well, your toolbox will look like this:

    ASP.NET AJAX 1

    That's it! AJAX has been installed, and its ready to be used. If you want the AJAX Control Toolkit controls in your toolbox, the procedure is similar, but you browse to "C:\Program Files\Microsoft ASP.NET\Ajax Control Toolkit\AjaxControlToolkit.dll". Now, onto the controls...

    The ScriptManager

    AJAX in ASP.NET 2.0 - Introduction To The Basics

    In a nutshell, the ScriptManager is the control that handles most of the behind the scenes Javascript side of AJAX. There must be a ScriptManager on any page that uses AJAX. The easiest way to achieve this is to put one at the top of the master page. As far as properties go, EnablePartialRendering is the single most important one to be familiar with. In a nutshell, it enables or disables asynchronous postbacks. Disabling partial rendering forces all postbacks to be full postbacks. This is extremely handy when debugging some errors, as the error provided with partial rendering is a small javascript popup.

    The UpdatePanel

    ASP.NET AJAX 3

    The UpdatePanel is the easiest way to use AJAX to improve the responsiveness of a web application using AJAX. When an event occurs that is deemed to be a trigger for the panel, the server processes the request and responds with the updated contents of the UpdatePanel INSTEAD of the contents of the entire page. What this means is that user interactions affecting a small area of the page will only cause that small area to refresh. This results in a sizable saving of bandwidth, and a noticeable increase in response time.

    UpdatePanels have a few important parameters that can require tweaking. ChildrenAsTriggers causes the panel to be refreshed when ever a child control fires an event. In some situations that is undesirable, as unnecessary asynchronous postbacks will occur. Triggers is a collection of control + events pairs on the page that will cause the update panel to refresh. This is my preferred way to specify when the contents of the panel are refreshed. UpdateMode specifies whether the update panel will refresh its contents on any postback or only those that trigger the panel. Again, I set this to 'Conditional' as it gives me finer control over when the panel is refreshed.

    The Timer

    ASP.NET AJAX 4

    This control is one that i had no use for during the first few months of developing, but after tinkering with the Timer it is extremely useful in some situations. A Timer fires a Tick event at regular intervals, and these ticks can be used as triggers for UpdatePanels. In other words, asynchronous postbacks can occur without any interaction from the user at all. This would come in handy for regularly saving the contents of a textbox or loading live stock prices for example. Timer has a couple of simple but useful properties, and these are Interval (the delay in milliseconds between tick events being fired) and Enabled (should the timer fire tick events or not).

    It is possible to get tricky and put a Timer inside an UpdatePanel, and change the Timer's properties at run time. By setting the Interval to a very small number, and then immediately disabling the timer in the tick event handler, only one tick event will occur. This is an effective way of running a section of code only when the page has finished loading in the client's browser.

    Sample ASP.NET AJAX Website Project

    The sample project I've included with this article uses all three of the described AJAX controls. It contains a ScriptManager at the top, an UpdatePanel which contains some labels whose contents will be changed and refreshed asynchonously, and a Timer to trigger the change in label text and cause the actual asynchronous postback.

    ASP.NET AJAX 5

    There is only 2 line of actual C# code in this simple project, and they set the label text to a random integer. Other than that, no additional coding was required to implement an AJAX'ed website. Pretty good eh'?

    From the use of 3 basic controls, anyone can AJAX up their projects, making them both better to use and more efficient to serve. There are a couple of other controls included in the ASP.NET AJAX Extensions that I haven't touched on here; they are the ScriptManagerProxy and UpdatProgress. I would strongly suggest that everyone muck around with the UpdateProgress control. From a usability point of view, it is essential to know when the page is performing behind the scenes, not just for the users of the site, but also the developers and debuggers.

    Attachments: SampleAJAXWebsite.zip 

  • Enhanced Calendar with Next/Previous Year Buttons

    By default, Visual Studio 2005 includes a useful range of components for building ASP.NET web applications. Unfortunately these components are usually very basic and have restricted usability, but with a small amount of customisation become highly usable.

    Enter the world of User Controls. A User Control uses regular ASP.NET components as building blocks to construct a more complex control that can be used in the same way as a regular component. User Controls can be assigned their own methods, properties, events, and be drag-and-dropped into ASP pages.

    In this post we will create a User Control that enhances the functionality of the basic Calendar control. We are going to adding buttons that go back and forward 1 year. Clearly when for browsing to dates many years ago or in the future, a simple next/previous month button is not sufficient. To select a date 5 years ago, 5 * 12 = 60 clicks would be required. With the successful implimentation of next and previous year buttons, this could be reduced to 5 clicks. A big win for usability. However, the challange here is where to locate our extra buttons within the user control to achieve a seamless layout. Overriding the Render(HtmlTextWriter) method will allow us to get the best result.

    Also, we will add a nullable SelectedDate property. The SelectedDate property of the standard Calendar must be assigned a value, which means it is difficult to have no selected date. As our SelectedDate can take on a null value (representing no selected date), a simple null check can be used to determine if a date has been selected by the user. As a result of this, form validation just became a whole lot simplier.

    Both the .ascx and .ascx.cs sample code files have been included with this post. Feel free to use these as a basis for adding other enhancements to the standard calendar, or even to start development of your own User Controls.

    First we need to create a new User Control for our enhanced calendar (I suggest creating a new folder called CustomControls and putting it in here). So right click on the destination of the control, select 'Add New Item', choose a Web User Control, and name it EnhancedCalendar.

    Creating the new User Control 1

    Creating the new User Control 2

    Now we are presented with a blank canvas that is our User Control. From the toolbox, drag over one Calendar control and two link button controls, and give these controls useful names (I have used calDate for the Calendar, btnPrevYear and btnNextYear for the buttons). Change the text for btnPrevYear to "<<"  and btnNextYear to ">>" and set both buttons to invisible (as we don't want them to render here). To match the existing interface of the calendar, I gave the buttons a tooltip which describes their function. To handle the selection of a date on calDate, give calDate a SelectionChanged event handler. Finally, give each of the buttons a Click event handler.

    Design view of the enhanced calendar

    That is all we need to do from a design point of view, now we move on to the code behind the scenes. Firstly create a property called SelectedDate, which will allow us to set and get the date represented by our enhanced calendar. I have chosen SelectedDate to be of type DateTime? (? makes it nullable) as the standard DateTime type is stored internally as a primative and thus is not nullable. For the button click event handlers, add or subtract one year from calDate.VisibleDate. Inside the calDate_SelectionChanged handler, we want to update our SelectedDate property with the latest value of calDate.SelectedDate. To be thorough, we should add a method to reset the date on our enhanced calendar, which I have called ResetDate().

    Next we need to alter how our user control is rendered. The procedure we are going to use will follow this basic flow:

    1. Render calDate to html and store in a string.
    2. Find the previous month link in the html string, and render btnPrevYear before it.
    3. Find the next month link in the html string, and render btnNextYear after it.
    4. Write this string as the html for our user control.

    Simple.

    The very first thing we need is a way of getting the rendered html code for a control. In our situation we want the html code for calDate. For this we will write a method called RenderToString(Control), which will render a control to html (regardless of its visibility). In theory this method should belong in a utility class, but for this example I have included it in our enhanced calendar's code. 

    The next things we need are two Regular Expressions that we can use to identify the next and previous month buttons in the stanrdard calendar's html code. By examining the html code of the standard calendar, the previous month button can be isolated by looking for a hyperlink with enclosed text of &lt;, and similarly the next month button by a hyperlink with enclosed text of &gt;. Once the regular expressions have been written, some static Regex objects are constructed to handle the matching.

    Now that we can identify the previous/next month links and render a control to html, we have all the tools required to insert our next/previous year buttons inside calDate. To perform the inserting we use a MatchEvaluator, which works by calling a target method when ever the Regex object finds a match. We will need to make the target method replace the next/previous month html with the next/previous month html concatenated with the rendered next/previous year button. Of course, two different methods are required; one for the next year and one for the previous year, as the order of the buttons is different. I have called these methods AppendPrevYear and AppendNextYear.

    Finally, all that is left to do is perform these steps in the overrided Render(HtmlTextWriter) method. First render calDate to a string, then insert the previous year year button, then insert the next year button, and then write the final html to the writer. And there you have it, that is all the code required to make our enhanced calendar.

    Original Calendar vs. Enhanced Calendar

    With these minor modifications, we now have a more usable (for both developer and end user) calendar control that can be used in the same way as the original. Additionally, it conforms to the same clean and uncluttered layout as the original calendar, which is a bonus. The addition of the next/previous year buttons make this control suitable (when combined with an ajax popup control extender for example) for use as a date selector input for a form. Also, the nullable SelectedDate means that validation of empty required date inputs can occur easily.

    For those readers who want to take this example further, some possible avenues for future development include:

    • expanded the regular expressions to collect the style attribute of the next/previous month hyperlink, and this could also be applied to the next/previous year buttons. This removes the need to synchronise style at compile time, with it instead occuring at run time.
    • add a method to the control specifically designed for use with a custom required field validator.
    • add more properties that set style attributes of calDate, so style information is not stored in the custom control, and this allow the same control to be used across multiple application.
Powered by Community Server (Personal Edition), by Telligent Systems