Wednesday, February 20, 2008

WebWeekly: Creating an AJAX-Enabled Calendar Control

4GuysFromRolla.com

Internet.com Network
Wednesday February 20, 2008

Creating an AJAX-Enabled Calendar Control
By Scott D. Smith

Introduction
Go to any travel or event booking website and you'll find the same user interface for collecting date information: the Calendar. Providing such an interface in an ASP.NET application is a breeze, thanks to the built-in Calendar Web control. There are two downsides to ASP.NET's Calendar control: first, it is not very useful when selecting dates far into the future or past, as you can only navigate to the next or previous month; and, second, the Calendar does not use AJAX techniques, so each click, be it selecting a date or moving to the next or previous month, requires a full postback.

Mehmet Genc addressed this first shortcoming in Extending the Calendar Control's Date Navigation by showing how to add month and year drop-down lists. But Mehmet's article was written in 2004 and since then AJAX-enabled websites have become all the rage. I decided it was high time to update Mehmet's custom Calendar control to support AJAX. Specifically, I implemented the AJAX-enabled Calendar control as a User Control. The User Control renders a TextBox control that, when clicked, displays a Calendar control from which the user can select the date. Like with Mehmet's Calendar, users can quickly jump to a particular month or year by using two drop-down lists. And best of all, the user experience is very responsive.

The AJAX-enabled Calendar control in action.

Read on to learn more!

First Things First: Ensuring Your Environment Supports ASP.NET AJAX
To use this AJAX-enabled Calendar control, make sure your development environment supports the ASP.NET AJAX framework. If you are using Visual Studio 2008, then this framework is already present. If, however, you are using Visual Studio 2005, then you need to download and install the ASP.NET AJAX framework from Microsoft's site, http://www.asp.net/ajax/. For more information on this process, refer to Scott Mitchell's article, AJAX Basics and Getting Started with Microsoft's ASP.NET AJAX Framework.

My AJAX-enabled Calendar control uses the UpdatePanel and PopupControlExtender controls. While the UpdatePanel is part of the framework's "Essential Components," the PopupControlExtender is part of the ASP.NET AJAX Control Toolkit, which is a separate download (even for Visual Studio 2008). If you check out the Control Toolkit samples you'll notice that there's an AJAX Calendar control in the Toolkit. I built my own AJAX-enabled Calendar control instead of using the one in the Control Toolkit because I wanted to add the month/year drop-down lists. Also, there have been a variety of display bugs with the Calendar control (see the AJAX Control Toolkit work item list). I invite you to try out mine and the AJAX Control Toolkit's Calendar and use the one that's best suited for your needs.

From the Internet.com eBook Library: Navigating Your IT Career

A career in information technology usually has its share of
ups and downs. Download this Internet.com eBook to learn
where the jobs are in IT, how to negotiate a salary, and
helpful advice on job security and how to deal with a layoff.
Join Internet.com now to download!
http://www.devx.com/ebook/Link/34938

Interested in placing your TEXT AD HERE? Click Here
 
Getting Started with My AJAX-Enabled Calendar Control
The complete code for this User Control, along with a sample web page, is available at the end of this article. You should be able to open the folder as a website in either Visual Studio 2005 or Visual Studio 2008.

The Calendar is implemented in the CoolCalendar.ascx file as a User Control. Take a moment to examine the markup in this page. You'll find the following key controls:

  1. The DateTextFrom TextBox
  2. A RequiredFieldValidator named DateTextFromRequired
  3. A Panel control
  4. An UpdatePanel control
  5. The month and year DropDownList controls
  6. The Calendar control
  7. An AJAX PopupControlExtender control
There are a few of these controls that warrant further discussion. Take note of the markup for the DateTextFrom TextBox control (item 1):

<asp:TextBox ID="DateTextFrom" Text="" runat="server" onFocus="javascript:this.blur();" Width="80" autocomplete="off" />

Note the onfocus="javascript:this.blur();". This bit of client-side script ensures that whenever the user clicks on the DateTextFrom TextBox, focus is immediately taken away from the control. The idea here - as we'll see shortly - is that whenever the user focuses on the TextBox it is immediately taken away and the Calendar control is displayed. This forces the user to select a date from the calendar. If you remove the onfocus script, the user could enter the date into the TextBox via the keyboard. I find this option undesirable due to the possibility of user entry errors.

The RequiredFieldValidator (item 2) is used to optionally ensure that a date value has been supplied. The User Control contains a Boolean public property named DateTextRequired. Setting this value to True enables the RequiredFieldValidator; setting it to False disables it. By default, the RequiredFieldValidator is enabled.

The AJAX PopupControlExtender control pops up a particular Panel on the page in response to a certain client-side action. The Panel control (item 3) defines the region that is popped up, and includes the UpdatePanel (item 4), the month/year DropDownLists (item 5), and the Calendar control (item 6).

The final piece in the markup page is the PopupControlExtender control (item 7) and is configured to display the Panel (item 3) whenever the DateTextFrom TextBox receives focus. This behavior is dictated entirely through the PopupControlExtender control's properties, there's no need to write any JavaScript or code!

<ajaxToolkit:PopupControlExtender ID="PopupControlExtender1" runat="server"
     TargetControlID="DateTextFrom"
     PopupControlID="Panel1"
     Position="Bottom" />

For more information on the PopupControlExtender see the PopupControlExtender Demonstration. Also check out Brian Smith's article, Displaying Extended Details in a GridView Using an Ajax Pop-Up.

Examining the AJAX-Enabled Calendar Control's Code
The User Control's code-behind class defines a couple of properties and includes the code to populate the month/year DropDownLists and the user's interactions with the Calendar. The most important property is the DateTextFromValue, which sets or gets the selected date. This property simply reads and writes its value to the DateTextFrom TextBox.

public string DateTextFromValue
{
    get { return DateTextFrom.Text; }
    set { DateTextFrom.Text = value; }
}

Note: The code available for download at the end of this article includes a VB and C# version of the User Control...

Two additional properties are defined for specifying whether the RequiredFieldValidator should be enabled (DateTextRequired) and the error message to display if the required date value is not supplied (DateTextRequiredText).

The month and year DropDownLists are populated by the Populate_MonthList and Populate_YearList methods, which are called on the first page visit. These methods were taken directly from Mehmet's article. Populate_MonthList returns a list of month names (January, February, ...) while Populate_YearList populates the DropDownList with years from 20 years ago to one year in the future.

When the month or year DropDownList is changed, a partial page postback occurs and the Set_Calendar method is executed. The Set_Calendar method sets the Calendar control's TodaysDate property to the first of the selected month/year.

public void Set_Calendar(object Sender, EventArgs E)
{
    string theDate = drpCalMonth.SelectedItem.Value + " 1, " + drpCalYear.SelectedItem.Value;

    DateTime dtFoo;
    dtFoo = System.Convert.ToDateTime(theDate);

    Calendar1.TodaysDate = dtFoo;
}

Whenever the user selects a date within the Calendar, a partial page postback transpires and the Calendar's SelectionChanged event is fired. The Calendar1_SelectionChanged event handler calls the PopupControlExtender control's Commit method, passing in the Calendar's SelectedDate property. The net effect is that the Calendar popup disappears and the selected date is display in the TextBox.

protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
    PopupControlExtender1.Commit(Calendar1.SelectedDate.ToShortDateString());
}

My AJAX-Enabled Calendar Web Control In Action
The download at the end of this article includes a simple demo page, TestCoolCalendar.aspx. The demo illustrates how to use the User Control's DateTextRequired and DateTextRequiredText properties to require a date and show a custom error message. In addition to the User Control, the TestCoolCalendar.aspx includes a Save button that, when clicked, displays the value selected from the Calendar control. This value is retrieved via the User Control's DateTextFromValue property.

Conclusion
In this article we saw how to use the ASP.NET AJAX framework's UpdatePanel and the AJAX Control Toolkit's PopupControlExtender to turn the built-in Calendar control into a richer, AJAX-enabled version. This control is implemented as a User Control, making it a cinch to add to your projects. If you have any questions or comments, you can contact me at ssmith@prairieheart.com. Thanks again to Mehmet Genc for the initial inspiration and to Scott Mitchell for publishing this article.

Happy Programming!

  • By Scott D. Smith


    About the Author:
    Scott D. Smith has an undergraduate degree in operating systems at Chico State University (CSU). He has been a database administrator and NET applications programmer for 6+ years at Prairie Cardiovascular Consultants. His Quality Treatment Plan webpages have been demonstrated around the world by Dr. James T. Dove, M.D., the president of the American College of Cardiology (ACA). If you have questions or comments about this article, email Scott at ssmith@prairieheart.com.

    Further Readings:

  • Extending the Calendar Control's Date Navigation
  • Displaying Extended Details in a GridView Using an Ajax Pop-Up
  • Building Interactive User Interfaces with Microsoft ASP.NET AJAX
  • The ASP.NET AJAX Framework
  • The ASP.NET AJAX Control Toolkit
  • Attachments

  • Download the Demo (in ZIP format)




  • JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

    All newsletters are sent from the domain "internet.com." Please use this domain name (not the entire "from" address, which varies) when configuring e-mail or spam filter rules, if you use them.

    No comments: