Using JQuery DatePicker in ASP.Net

I’ve had a number of uses for a more configurable date picker on my current application.  I needed something that looked good, and I one that I could set constraints for (Min and Max dates).  That last problem basically made the AJAX Toolkit CalendarExtender out of the running.

Luckily I found the JQuery DatePicker.  This used be a separate download, you can find the original here, but it is now part of JQuery.UI.

But first, there are a few tricks to using it (or any other JavaScript control for that matter).  First things first, this is not a separate server control that replaces the text box with a date friendly text box.  This is a javascript library that extends a standard text box and gives it date functionality.

So the first thing you have to do is put a text box on your form.

<asp:TextBox ID="DateTextBox" runat="server" />

Next on my list is to add the DatePicker JavaScript file, ui.datepicker.js.  I still use the Microsoft AJAX Library which has the nice ScriptManager control, so typically I use that control to add my JavaScript files to the page.

<link rel="stylesheet" href="~\Scripts\ui.datepicker.css" type="text/css" media="screen"  charset="utf-8" />
<asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server">
    <Scripts>
        <asp:ScriptReference Path="~/Scripts/jquery.js" />
        <asp:ScriptReference Path="~/Scripts/ui.datepicker.js"  />
    </Scripts>
</asp:ScriptManagerProxy>

Note: I also included a link to the CSS file used to “skin” the calendar control.

Now everything is in place, we still  have to tell the javascript which text box control (DateTextBox) to put a Calendar control on.  I typically make a quick little JavaScript function that I can call to hook them up.  It looks like this:

function LoadDateControls() {
    $('#<%= DateTextBox.ClientID %>').attachDatepicker(); 
}

This code block asks the ASP.Net page for the ClientId of the text box control (very handy when dealing with Master Pages or User Control), and then attaches the date picker to the text box.

OK, the final bit of hooking up we have to do is call this function once the page is loaded and ready.  If we are using the Microsoft AJAX Library then you can use the pageLoad method like this:

function pageLoad(sender, args) {
    LoadDateControls();
}

If you want to stick with “pure” JQuery then you can do this instead:

$(document).ready(function() {
   LoadDateControls();
 });

Either way works, it is up to you which you like better.

JQueryCalendarSo lets review where we are now.  We have added the JavaScript to our page, and pointed it at a text box to display a calendar.  If everything has gone according to plan, you should see something like what you see to the right when you click on the text box.

I like it.  And as far as I know all of the colors and fonts are configurable via css.

OK, that covers most of my requirements, but there was one other requirement that isn’t here yet: Min and Max dates.

This one is a little harder.  First we have to know what Min and Max dates to use, and that will have to come from the code behind.  Assuming you know that, you can call this C# code:

protected string MinDate;
protected string MaxDate;
 
private void UpdateDateRangeContols(DateTime minDate, DateTime maxDate)
{
    MinDate = EncodeJsDate(minDate);
    MaxDate = EncodeJsDate(maxDate);
}
 
public string EncodeJsDate(DateTime date)
{
    return date.ToString("U") + " UTC";
}

Now I have a MinDate and MaxDate fields that I can access from my aspx page.  To do that I’m going to rewrite my LoadDateControls function to look like this:

function LoadDateControls() {
 <%
    Response.Write("$.datepicker.setDefaults({dateFormat:'m/d/yy', minDate: new Date('"+MinDate+"'), maxDate:new Date('"+MaxDate+"')});");
 %>
    $('#<%=DateTextBox.ClientID %>').attachDatepicker();
}

One side effect of that bit of code is that I also use it to specify the date format.

But wait, did I really just use a Response.Write in my ASP.Net file?  Isn’t that old school and lame?  Old school: yes.  Lame: no (if used in moderation).  I’m note writing an entire web site using Response.Write, just setting some JavaScript.  Besides, if you want to be one of the cool kids and start using the MVC framework, you had better get used to Response.Write again.  You’re going to need it.

In my code behind, I set my calendar controls to only allow date entries that go back 2 weeks.  Take a look at what we get.

JQueryCalendar2

Today’s date is May 6 (highlighted in pink), so my date range is April 28 to May 11.  When you are on the month of May, the Next button is disabled.  And, if I hit the drop downs for Month I only see April and May, and for Year I only get 2008.  Same for April, I can’t go to March.

OK, so what if all of this is too much for you.  This is too much code, to much work, all you want is darn server control to use.  You are in luck.  Head over to West Wind Technologies and pick up Rich Strahl’s JQuery Calendar ASP.Net Control.  Also subscribe to his blog, he is usually worth the read.

9 thoughts on “Using JQuery DatePicker in ASP.Net

  1. I am in the prototype camp (for reasons I specified at my Code Camp presentation), and I’ve had some good luck turning http://code.google.com/p/calendardateselect/ into a ASP.NET Control.

    One thing I like about it is you can specify a JS callback function to determine what dates are valid. So, you can specify any arbitrary set of invalid dates, such as weekends, or less than 2 weeks after some other field, or days with full moons, or whatever.

    Otherwise, it has a pretty similar set of features as this JQuery one.

  2. I got the datepicker working, however when i added a RequiredFieldValidator to check that field, i would get a JavaScript error. Has anyone found a workaround or solution for this?

  3. Hi,
    I want trim the JQuery.js file and Ui.Datepicker.js
    My requirement is simple when click on Image button calender should display.

  4. steve this suman u must serch in google any functioinality will get yaar no need to ask anyone we should try evenialso trying

  5. Hi, I am new to jquery and programing.. I followed your instruction and i am getting object does not support this property on  $(‘#’).attachDatepicker(); line… I could not find attacheDatepicker() function anywhere.. am i missing something?

Comments are closed.

Proudly powered by WordPress | Theme: Code Blog by Crimson Themes.