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

image

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

image

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 – ViewsHomeIndex.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 – ViewsHomeCreate.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

image

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

Discussion

  1. http:// says:

    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

  2. http:// says:

    looking in the source of the control toolkit seems to be not very difficult modify your code to implement helper for client only extenders, but i think to handle extenders as autocomplete and dropdowncascading totally inside mvc is more difficult, because these controls make calls to webservices or page methods, and i don’t understand how to create actions that answers correctly to the control. if i can suggest the subject of a future post, i suggest this .

  3. I’m curious as to how this is better than say using the Frequency Decoder date picker (http://www.frequency-decoder.com/…/unobtrusive-date-...) 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.

  4. http:// says:

    @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.

  5. http:// says:

    @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.

  6. http:// says:

    @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

  7. http:// says:

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

  8. http:// says:

    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?

  9. http:// says:

    great!great!great!

  10. 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: damianblog.com/…/mvc-control-toolkit-dependen…

    /Damian

  11. http:// says:

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

  12. SexOrgy says:

    Private sex orgy online. Free amateurs party in New York.

  13. Don says:

    I have enjoyed your blog and have used a number of your MVC tips.

    I used this popup calendar code in an online ‘job application’ application I wrote within a week or two after this original post and it works great using the VS development web server…. but when i run as an IIS7 web app the javacript code: fails with ‘Sys not defined’. (This is the only ajax js feature I am using.)

    My application runs perfect with the VS development web server.

  14. Roslyn says:

    Hi,

    Is it possible to set the date to date format dd/mm/yyyy.

    Also is it possible to set the calendar to start at a certain date for example 1 January 2000.

    Thanks

  15. Stealth says:

    2 Roslyn:
    $create(AjaxControlToolkit.CalendarBehavior, { format: “dd.MM.yyyy” }, null, null, $get(‘PublishedDate’));

    Question:
    how about localization of calendar?
    if i want to show it for ru-RU cultufe or another.

  16. MOV to DVD says:

    The best MVC approach is Java Struts. All the others (including ASP.NET) suck!

  17. Sunil says:

    Hi
    I m new to ASP.Net MVC and when trying to run the sample i am getting the following error
    “Compiler Error Message: CS1705: Assembly ‘Tip36, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null’ uses ‘System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35′ which has a higher version than referenced assembly ‘System.Web.Routing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35′”
    can anyone help me out

  18. Be support for database should not be over-used but at the same time, it is a required feature.

  19. Alexander says:

    Hi,

    Great example!

    I have one problem though. When running my app in debug mode everything is working fine. After deploying my app I get a “Sys is not defined” error though.

    Any ideas?

  20. Khun says:

    Hi !
    Great code !

    I try to study about this function. But is not clear. Can you tell me about this function
    $create(AjaxControlToolkit.CalendarBehavior, null, null, null, $get(‘PublishedDate’));
    how can I put variable for ‘null’ value ?

  21. RW W Great article, though – thanks!

  22. 44 Thank you for sharing the this code.

  23. really nice post, thanks a lot.

  24. HD Video Converter says:

    As the users of HD Camcorders like Sony, Canon, Panasonic, this HD Video Converter is necessary to help us convert hd Video easily and quickly. The Converter for HD provides several practical editing functions to help you achieve ideal output effect. Trim function is to cut videos into clips which you can just convert and transfer to your player. Crop function helps you remove black bars around the movie. You could use Effect function to adjust video brightness, contrast, saturation and more parameters. More powerful and considerate functions are waiting for you to explore.MKV Converter l FLV Converter l DVD Ripper !!