ASP.NET MVC Tip #36 – Create a Popup Calendar Helper
In this tip, Stephen Walther demonstrates how you can create a JavaScript popup calendar (date picker) that works within an ASP.NET MVC view. The calendar is created with the AJAX Control Toolkit.
A script file only version of the AJAX Control Toolkit was just released by Microsoft at the CodePlex website:
http://www.codeplex.com/AjaxControlToolkit/Release/ProjectReleases.aspx?ReleaseId=16488
This version of the AJAX Control Toolkit does not contain server-side controls or control extenders. It contains only the client-side files – JavaScript, CSS, images – required to use the client-side AJAX behaviors.
This is great news for ASP.NET MVC developers. It means that we can easily take advantage of the client-side AJAX behaviors contained in the AJAX Control Toolkit in our MVC views. For example, we can create auto-complete input fields, modal dialog boxes, and rich animations. In this tip, I demonstrate how you can add a popup calendar to an HTML form input field which you can use as a fancy date picker (see Figure 1).
Figure 1 – Using the AJAX Calendar Behavior
I am a big fan of the AJAX Calendar behavior. It supports fancy animations. For example, when you click on the name of the month, a menu of months scrolls into view.
In this tip, I explore two methods of using the AJAX Calendar behavior. First, I explain how you can use the Calendar behavior by including a set of JavaScript, CSS, and image files in your view. Next, I explain how you can create a HTML Helper that adds all of the required files automatically.
Adding the Calendar Behavior to a View by Hand
Adding any of the behaviors from the AJAX Control Toolkit to a view by hand takes some work. The problem is that you must include several JavaScript libraries, in the right order, to use the behavior. In this section, I walk through the process of adding the Calendar behavior to a view. In the next section, I demonstrate how you can avoid this work.
Step 1 – Add the AJAX Control Toolkit Folder to Your Application
Download the client file only version of the AJAX Control Toolkit from the following location:
http://www.codeplex.com/AjaxControlToolkit/Release/ProjectReleases.aspx?ReleaseId=16488
After you unzip the download, copy the AjaxControlToolkit folder into the Content folder in your ASP.NET MVC application.
There are a lot of files in the AjaxControlToolkit folder (the folder is a little over a megabyte in size). However, you’ll need to reference several files in the folder to use the Calendar behavior. Because, most likely, you’ll end up using several AJAX behaviors, I recommend just dumping the whole folder into your MVC application.
After you add the folder, your Solution Explorer window should resemble Figure 2.
Figure 2 – ASP.NET MVC Application with AJAX Control Toolkit files
Step 2 – Include the Required Files in Your View
This is the most time-consuming step. You must add all of the JavaScript and CSS files required by the Calendar behavior to the view in which you want to use the behavior (alternatively, you can include these files in a master page).
In order to use the Calendar behavior, you need to include all of the JavaScript files, and the single CSS file, in Listing 1.
Listing 1 – \Views\Home\Index.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="Tip36.Views.Home.Index" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Index</title> <link href="../../Content/AjaxControlToolkit/3.0.20820.16598/3.0.20820.0/AjaxControlToolkit.Calendar.Calendar.css" rel="stylesheet" type="text/css" /> <script src="../../Content/MicrosoftAjax.debug.js" type="text/javascript"></script> <script src="../../Content/AjaxControlToolkit/3.0.20820.16598/3.0.20820.0/AjaxControlToolkit.ExtenderBase.BaseScripts.js" type="text/javascript"></script> <script src="../../Content/AjaxControlToolkit/3.0.20820.16598/3.0.20820.0/AjaxControlToolkit.Common.Common.js" type="text/javascript"></script> <script src="../../Content/AjaxControlToolkit/3.0.20820.16598/3.0.20820.0/AjaxControlToolkit.Common.DateTime.js" type="text/javascript"></script> <script src="../../Content/AjaxControlToolkit/3.0.20820.16598/3.0.20820.0/AjaxControlToolkit.Animation.Animations.js" type="text/javascript"></script> <script src="../../Content/AjaxControlToolkit/3.0.20820.16598/3.0.20820.0/AjaxControlToolkit.PopupExtender.PopupBehavior.js" type="text/javascript"></script> <script src="../../Content/AjaxControlToolkit/3.0.20820.16598/3.0.20820.0/AjaxControlToolkit.Animation.AnimationBehavior.js" type="text/javascript"></script> <script src="../../Content/AjaxControlToolkit/3.0.20820.16598/3.0.20820.0/AjaxControlToolkit.Common.Threading.js" type="text/javascript"></script> <script src="../../Content/AjaxControlToolkit/3.0.20820.16598/3.0.20820.0/AjaxControlToolkit.Compat.Timer.Timer.js" type="text/javascript"></script> <script src="../../Content/AjaxControlToolkit/3.0.20820.16598/3.0.20820.0/AjaxControlToolkit.Calendar.CalendarBehavior.js" type="text/javascript"></script> <script type="text/javascript"> Sys.Application.add_init(appInit); function appInit() { $create(AjaxControlToolkit.CalendarBehavior, null, null, null, $get('birthDate')); } </script> </head> <body> <div> <form method="post" action="/Home/Insert"> <label for="birthDate">Birth Date:</label> <br /> <input id="birthDate" name="birthDate" /> <br /><br /> <input type="submit" value="Add" /> </form> </div> </body> </html>
You must add the JavaScript files in the right order. One JavaScript file might depend on functionality defined in another JavaScript file.
Step 3 – Create the Behavior
The final step is to create the Calendar behavior and associate it with an input field. Notice that the view in Listing 1 contains the following script:
<script type="text/javascript"> Sys.Application.add_init(appInit); function appInit() { $create(AjaxControlToolkit.CalendarBehavior, null, null, null, $get('birthDate')); } </script>
You create client-side AJAX controls and behaviors during the client-side Application init event. This script registers an event handler for this event that calls the $create() method to create the Calendar behavior.
The $create() method accepts the following parameters:
· type – The type of client-side component, control, or behavior to create
· properties – A JavaScript object literal that represents a set of property names and values
· events – A JavaScript object literal that represents a set of event names and handlers
· references – A JavaScript object literal that represents a set of property names and references to other components
· element – The DOM element to which the client-side component, control, or behavior is attached
In Listing 1, the Calendar behavior is attached to the birthDate input field contained in the HTML form located in the body of the view.
After you complete this step, the Calendar behavior works in the view. When you click in the birth date field (or tab to the field) the calendar appears.
Adding the Calendar Behavior to a View with an HTML Helper
In the previous section, we added the Calendar behavior to a view by hand. The hardest part of the process was adding all of the files required by the Calendar. In this section, we create an HTML Helper that adds all of the required files automatically.
We will need to create a couple of helper classes before we can create our Calendar class. The first class that we need to make is something called the ResourceTracker class. This class is contained in Listing 2.
Listing 2 – ResourceTracker.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; namespace AjaxControlToolkitMvc { public class ResourceTracker { const string resourceKey = "__resources"; private List<string> _resources; public ResourceTracker(HttpContextBase context) { _resources = (List<string>)context.Items[resourceKey]; if (_resources == null) { _resources = new List<string>(); context.Items[resourceKey] = _resources; } } public void Add(string url) { url = url.ToLower(); _resources.Add(url); } public bool Contains(string url) { url = url.ToLower(); return _resources.Contains(url); } } }
The reason that we need the ResourceTracker class is to prevent us from adding the same script or CSS file to a page more than once. Imagine that you need two Calendar input fields (for example, a start and end date). In that case, you do not want to add all of the necessary JavaScript files twice because adding all of these files would slow down your page. The ResourceTracker verifies whether or not a resource with a certain URL has already been added.
The ResourceTracker uses the HttpContext.Items collection. This collection survives a single browser request. This is what we want. We don’t want to include a JavaScript file more than once within a single browser request for a single user.
The class in Listing 3 adds a single utility method for adding JavaScript file includes.
Listing 3 – ScriptExtensions.cs
using System.Text; using System.Web.Mvc; namespace AjaxControlToolkitMvc { public static class ScriptExtensions { public static string ScriptInclude(this AjaxHelper helper, params string[] url) { var tracker = new ResourceTracker(helper.ViewContext.HttpContext); var sb = new StringBuilder(); foreach (var item in url) { if (!tracker.Contains(item)) { tracker.Add(item); sb.AppendFormat("<script type='text/javascript' src='{0}'></script>", item); sb.AppendLine(); } } return sb.ToString(); } } }
Notice that the class in Listing 3 takes advantage of the ResourceTracker class. Imagine that you call the ScriptInclude() helper method multiple times in a page like this:
<%= Ajax.ScriptInclude(“/scripts/myLibrary.js”) %>
<%= Ajax.ScriptInclude(“/scripts/myLibrary.js”) %>
<%= Ajax.ScriptInclude(“/scripts/myLibrary.js”) %>
In that case, the myLibrary.js file will be included in the page only once. The ResourceTracker prevents the script from being included multiple times.
Next, we need to create a utility class for generating URLs to the Microsoft Ajax Library and the Ajax Control Toolkit files. This class is contained in Listing 4.
Listing 4 – AjaxExtensions.cs
using System; using System.Text; using System.Web.Mvc; namespace AjaxControlToolkitMvc { public static class AjaxExtensions { private static string _microsoftAjaxLibraryUrl = "/Content/MicrosoftAjax.js"; private static string _toolkitFolderUrl = "/Content/AjaxControlToolkit/3.0.20820.16598/3.0.20820.0/"; public static void SetMicrosoftAjaxLibraryUrl(this AjaxHelper helper, string url) { _microsoftAjaxLibraryUrl = url; } public static string GetMicrosoftAjaxLibraryUrl(this AjaxHelper helper) { return _microsoftAjaxLibraryUrl; } public static void SetToolkitFolderUrl(this AjaxHelper helper, string url) { _toolkitFolderUrl = url; } public static string GetToolkitFolderUrl(this AjaxHelper helper) { return _toolkitFolderUrl; } public static string MicrosoftAjaxLibraryInclude(this AjaxHelper helper) { return ScriptExtensions.ScriptInclude(helper, _microsoftAjaxLibraryUrl); } public static string ToolkitInclude(this AjaxHelper helper, params string[] fileName) { var sb = new StringBuilder(); foreach (string item in fileName) { var fullUrl = _toolkitFolderUrl + item; sb.AppendLine( ScriptExtensions.ScriptInclude(helper, fullUrl)); } return sb.ToString(); } public static string DynamicToolkitCssInclude(this AjaxHelper helper, string fileName) { var fullUrl = _toolkitFolderUrl + fileName; return helper.DynamicCssInclude(fullUrl); } public static string DynamicCssInclude(this AjaxHelper helper, string url) { var tracker = new ResourceTracker(helper.ViewContext.HttpContext); if (tracker.Contains(url)) return String.Empty; var sb = new StringBuilder(); sb.AppendLine("<script type='text/javascript'>"); sb.AppendLine("var link=document.createElement('link')"); sb.AppendLine("link.setAttribute('rel', 'stylesheet');"); sb.AppendLine("link.setAttribute('type', 'text/css');"); sb.AppendFormat("link.setAttribute('href', '{0}');", url); sb.AppendLine(); sb.AppendLine("var head = document.getElementsByTagName('head')[0];"); sb.AppendLine("head.appendChild(link);"); sb.AppendLine("</script>"); return sb.ToString(); } public static string Create(this AjaxHelper helper, string clientType, string elementId) { var sb = new StringBuilder(); sb.AppendLine("<script type='text/javascript'>"); sb.AppendLine("Sys.Application.add_init(function(){"); sb.AppendFormat("$create({0},null,null,null,$get('{1}'))", clientType, elementId); sb.AppendLine("});"); sb.AppendLine("</script>"); return sb.ToString(); } } }
The most interesting method in the AjaxExtensions class is the DynamicCssInclude() method. This method adds an HTML <link rel=’stylesheet’ type=’text/css’> tag to the head of the XHTML document.
Adding a link to a CSS file in the body of a document fails XHTML validation (and it just won’t work in Internet Explorer). Therefore, the DynamicCssInclude() method renders JavaScript code that injects the CSS link into the head of the document dynamically.
Finally, we are ready to create a helper that renders the Calendar behavior. The Calendar helper is contained in Listing 5.
Listing 5 – CalendarExtensions.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Mvc; namespace AjaxControlToolkitMvc { public static class CalendarExtensions { public static string Calendar(this AjaxHelper helper, string elementId) { var sb = new StringBuilder(); // Add Microsoft Ajax library sb.AppendLine(helper.MicrosoftAjaxLibraryInclude()); // Add toolkit scripts sb.AppendLine( helper.ToolkitInclude ( "AjaxControlToolkit.ExtenderBase.BaseScripts.js", "AjaxControlToolkit.Common.Common.js", "AjaxControlToolkit.Common.DateTime.js", "AjaxControlToolkit.Animation.Animations.js", "AjaxControlToolkit.PopupExtender.PopupBehavior.js", "AjaxControlToolkit.Animation.AnimationBehavior.js", "AjaxControlToolkit.Common.Threading.js", "AjaxControlToolkit.Compat.Timer.Timer.js", "AjaxControlToolkit.Calendar.CalendarBehavior.js" )); // Add Calendar CSS file sb.AppendLine(helper.DynamicToolkitCssInclude("AjaxControlToolkit.Calendar.Calendar.css")); // Perform $create sb.AppendLine(helper.Create("AjaxControlToolkit.CalendarBehavior", elementId)); return sb.ToString(); } } }
The Calender() helper method takes advantage of the utility classes that we just created. The method adds the Microsoft Ajax Library to the page (if it hasn’t already been added), adds all of the necessary toolkit files (if they have not already been added), and calls the Microsoft AJAX Library $create() method to create the Calendar behavior.
The view in Listing 6 uses the Calendar() helper to display two popup JavaScript calendars.
Listing 6 – \Views\Home\Create.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Create.aspx.cs" Inherits="Tip36.Views.Home.Create" %> <%@ Import Namespace="AjaxControlToolkitMvc" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Create</title> </head> <body> <div> <form method="post" action="/Home/Insert"> <label for="startDate">Start Date:</label> <br /> <input id="startDate" name="birthDate" /> <%= Ajax.Calendar("startDate") %> <br /><br /> <label for="endDate">End Date:</label> <br /> <input id="endDate" name="endDate" /> <%= Ajax.Calendar("endDate") %> <br /><br /> <input type="submit" value="Add" /> </form> </div> </body> </html>
In Listing 6, the Ajax.Calendar() helper is called twice. Both the start date and end date input fields display a popup calendar. Even though the Calender() method is called twice, only one copy of all of the files are added to the view. You can verify by using Firebug (see Figure 3).
Figure 3 – Using Firebug to verify the number of scripts downloaded
Summary
In this tip, I discussed two methods of displaying a popup JavaScript calendar in an MVC view. In the first part of this blog entry, I demonstrated how you can add the Calendar behavior to a view by hand. Next, we created an Ajax.Calendar() helper that performs all of the work for us.
The same techniques discussed in this tip can be applied to any of the other behaviors in the Microsoft Ajax Control Toolkit. You can create helpers for creating auto-complete text fields, modal dialog boxes, and watermarks. In future tips, I’ll explore these additional possibilities.