web 2.0

MVC - Using the jQuery DatePicker

jQuery is the greatest thing since sliced bread. The amount of functionality built into those javascript libraries is absolutely amazing (Thanks to John Resig!). Today, while I was working on my company website I discovered that I really need some sort of datepicker for one of my admin pages. Luckily, the whole process of adding a datepicker only takes seconds with the jQuery UI libraries.

  1. Visit the jQuery UI download page. On the right hand side of the page you will see a download button. However, before you hit that button you may want to select a theme first. For my demo I chose black-tie because it matches the color scheme of my site. Also, notice that you can customize the download to include/exclude functionality. This is good if you want to reduce the size of the javascript file to make browsing faster for your users. Anyway, once you finish your customization (for the sake of this demo, make sure you do not uncheck the Datepicker) click the Download button.
  2. Add the script and optional style sheet references to your webpage. Mine looks like this, but you may need to customize yours to match your directory structure:
  3. <script src="/Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
    <script src="/Scripts/jquery-ui-1.7.2.custom.min.js" type="text/javascript"></script>
    <link rel="stylesheet" type="text/css" href="/Scripts/jquery-ui-1.7.2.custom.css" />
  4. Add the HTML code to your page. You have two options here..
    • Without Using HtmlHelper:
      <script type="text/javascript"> 
         $(document).ready(function(){ 
            $("#FromDate").datepicker(); 
         }); 
      </script> 
      <input type="text" id="FromDate" name="FromDate" value=""/> 
    • With HtmlHelper: (recommended method because it will clean up your source code and lend itself to reusability)
      Create a new class in your MVC project.
      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Web;
       
      namespace System.Web.Mvc.Html {
          public static class DatePickerExtension {
              public static string DatePicker(this HtmlHelper htmlHelper, string name, string value )
              {
                  return "<script type=\"text/javascript\">" +
                           "$(function() {" +
                           "$(\"#" + name + "\").datepicker();" +
                           "});" +
                           "</script>" +
                           "<input type=\"text\" size=\"10\" value=\"" + value + "\" id=\"" + name + "\" name=\"" + name + "\"/>";             
              }
          }
      }
      Now you can use the extension method you created to insert the html code and script...
      <%= Html.DatePicker( "Date", Html.Encode(String.Format("{0:MM/dd/yyyy}", Model.Date)) ) %> 

And here are the results...

Additional Resources:

blog comments powered by Disqus