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

clip_image002

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

clip_image004

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

clip_image006

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.

Download the Code

30 Comments

  • really nice post, thanks a lot.
    where can i find more informations on the file dependencies that every behavior have? i would like to create more extension to use other toolkit behaviors from mvc applications

  • I'm curious as to how this is better than say using the Frequency Decoder date picker (http://www.frequency-decoder.com/2006/10/02/unobtrusive-date-picker-widgit-update) which involves linking to one script file, one css file and adding a simple class declaration to any input field (or set of dropdownlists if you wish) you wish to add the date picker to. I know which one I would use.

  • @BrianOConnell - Using the Toolkit Calendar behavior is not necessarily better than using another JavaScript date picker implementation. The cool thing is that Microsoft has a big bag of goodies (the AJAX Toolkit) and with the release of the client file only library, we can start playing with all of these goodies in our MVC applications.

    I'll have to look into the Frequency Decoder date picker -- it looks like it has a lot of rich functionality.

  • @Luca Morelli - Download the full AJAX Control Toolkit and take a look at the debug versions of the JavaScript files. They contain a list of references at the top of the file to other JavaScript file dependencies.

  • @swalther - done, i tried and works fine with only client behaviors, the problem is with autocomplete and cascading that require calls to webservices or page methods

  • Is there an option to combine JS files like toolkit scriptmanager does?

  • Is there a way to write the JS script include files to the head tag or possibly to the Master Page head content area?
    I'm curious as to some pointers on how to go about this?

  • great!great!great!

  • FWIW I've written some server-side code that automatically works out the dependencies for a particular AJAX Control Toolkit control and serves all the required JavaScript in one go: http://damianblog.com/2008/10/22/mvc-control-toolkit-dependencies/

    /Damian

  • Awesome article. This has helped me with a particular project that I have been working on for two weeks.

  • How can I add popup button to callendar?

  • This is great. Thanks for this.

    BTW ... how to setup to Australian date format? DD/MM/YYYY?

  • Asp net mvc tip 36 create a popup calendar helper.. Slap-up :)

  • aesthetic surgery cosmetic surgery and aesthetic more

  • It's going to be ending of mine day, except before ending I am reading this wonderful piece of writing to increase my knowledge.

  • I was recommended this blog by my cousin.
    I am not sure whether this post is written by him as nobody else know such detailed
    about my problem. You are incredible! Thanks!

  • What's Going down i am new to this, I stumbled upon this I have discovered It positively helpful and it has aided me out loads. I'm hoping to give a contribution & assist different users like
    its helped me. Great job.

  • Hey there! I just wanted to ask if you ever have any trouble with hackers?
    My last blog (wordpress) was hacked and I ended up losing many months of hard work
    due to no backup. Do you have any methods to protect against hackers?

  • Oh my goodness! Amazing article dude! Many thanks, However
    I am going through troubles with your RSS. I don't know the reason why I can't join it.
    Is there anybody having identical RSS issues? Anyone that knows the answer
    can you kindly respond? Thanks!!

  • Hi there, yup this post is genuinely pleasant and I have learned
    lot of things from it on the topic of blogging.
    thanks.

  • Thanks very nice blog!

  • My relatives every time say that I am wasting my time here at net, except I know I
    am getting familiarity all the time by reading
    thes nice articles.

  • Having read this I thought it was extremely informative.
    I appreciate you spending some time and energy to put this informative
    article together. I once again find myself personally spending way too much time
    both reading and leaving comments. But so what, it was still worth it!

  • Have you ever thought about including a little bit more than
    just your articles? I mean, what you say is valuable and everything.
    However think about if you added some great images or videos to give your posts more, "pop"!
    Your content is excellent but with pics and clips, this blog could certainly be one
    of the best in its niche. Awesome blog!

  • Thanks for sharing your thoughts on ASP.NET MVC.
    Regards

  • I every time used to read post in news papers but now as I am a user of net therefore from now I am using
    net for articles, thanks to web.

  • Thanks designed for sharing such a good thinking, article
    is pleasant, thats why i have read it fully

  • My brother recommended I might like this website.
    He was entirely right. This post truly made my day.
    You cann't imagine simply how much time I had spent for this info! Thanks!

  • I loved as much as you will receive carried out right here.
    The sketch is tasteful, your authored material stylish.
    nonetheless, you command get bought an impatience over
    that you wish be delivering the following.

    unwell unquestionably come more formerly again since exactly the same nearly very often inside case
    you shield this hike.

  • Why viewers still make use of to read news papers when in this technological world the whole thing is presented on net?

Comments have been disabled for this content.