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.
So the first thing you have to do is put a text box on your form.
Note: I also included a link to the CSS file used to “skin” the calendar control.
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:
If you want to stick with “pure” JQuery then you can do this instead:
Either way works, it is up to you which you like better.
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:
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:
One side effect of that bit of code is that I also use it to specify the date format.
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.
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.