Ala'a Alnajjar

Everything about ASP.Net

How to use jQuery Date Range Picker plugin in asp.net

I stepped by this page: http://www.filamentgroup.com/lab/date_range_picker_using_jquery_ui_16_and_jquery_ui_css_framework/ and let me tell you,this is one of the best and coolest daterangepicker in the web in my opinion,they did a great job with extending the original jQuery UI DatePicker.Of course I made enhancements to the original plugin (fixed few bugs) and added a new option (Clear) to clear the textbox. In this article I well use that updated plugin and show you how to use it in asp.net..you will definitely like it.

So,What do I need?

1- jQuery library : you can use 1.3.2 or 1.4.2 which is the latest version so far,in my article I will use the latest version.
2- jQuery UI library (1.8): As I mentioned earlier,daterangepicker plugin is based on the original jQuery UI DatePicker so that library should be included into your page.
3- jQuery DateRangePicker plugin : you can go to the author page or use the modified one (it's included in the attachment),in this article I will use the modified one.
4- Visual Studio 2005 or later : very funny :D[as if you don't already knows that],anyway in my article I will use VS 2008.

Note: in the attachment,I included all CSS and JS files so don't worry.

How to use it?







Then add this html:


First Date:
Second Date:

As you can see,it includes TextBox1 which we are going to attach the daterangepicker to it,2 labels to show you later on by code on how to read the date from the textbox and set it to the labels
Now we have to attach the daterangepicker to the textbox by using jQuery (Note:visit the author's website for more info on daterangerpicker's options and how to use them):


Finally,add this C# code:
protected void SubmitButton_Click(object sender, EventArgs e)
    {
        if (TextBox1.Text.Trim().Length == 0)
        {
            return;
        }
        string selectedDate = TextBox1.Text;

        if (selectedDate.Contains("-"))
        {
            DateTime startDate;
            DateTime endDate;
            string[] splittedDates = selectedDate.Split("-".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            if (splittedDates.Count() == 2 && DateTime.TryParse(splittedDates[0], out startDate) && DateTime.TryParse(splittedDates[1], out endDate))
            {
                FirstDate.Text = startDate.ToShortDateString();
                SecondDate.Text = endDate.ToShortDateString();
            }
            else
            {
                //maybe the client has modified/altered the input i.e. hacking tools
            }
        }
        else
        {
            DateTime selectedDateObj;
            if (DateTime.TryParse(selectedDate, out selectedDateObj))
            {
                FirstDate.Text = selectedDateObj.ToShortDateString();
                SecondDate.Text = string.Empty;
            }
            else
            {
                //maybe the client has modified/altered the input i.e. hacking tools
            }
        }
    }

This is the way on how to read from the textbox,That's it!.

FAQ:

1-Why did you add this style?:
    

A:For two reasons:
  • To show the Daterangepicker in a smaller size because it's original size is huge.
  • To show you how to control the size of it.

2- Can I change the theme?
A: yes you can,you will notice that I'm using Redmond theme which you will find it in jQuery UI website,visit their website and download a different theme,you may also have to make modifications to the css of daterangepicker,it's all yours.

3- Why did you add a font size to the textbox?
A: To make the design look better,try to remove it and see by your self.

4- Can I register the script at codebehind?
A: yes you can

5- Why do I need to set attributes (readonly) and (unselectable) for the textbox ?


A:readonly will make the textbox not editable by the user,unselectable will block the blinking typing cursor from appearing if the user clicked on the textbox,you will notice that both attributes are necessary to be used together,you can't just use one of them...for logical reasons of course.

Finally,I hope everyone liked the article and as always,your feedbacks are always welcomed and if anyone have any suggestions or made any modifications that might be useful for anyone else then please post it here and at at the author's website.

P.S : There is no harm in posting comments

Comments

Diana said:

Thanks for posting this.  When I tried plugging in the JS + CSS from the original Filament Group article, it didn't work. But plugging in your versions from the attachment archive works! I'm not sure if you made changes to the code (it appears so when I compared the before and after file sizes), but thanks a lot!

# June 9, 2010 8:15 PM

alaa9jo said:

Thanks Diana,Yes I made a lot of changes to the JS and maybe to the css file as well. Anyway it should work if you used the JS and css files from the original Filament Group article so I'm sure you are missing something or did something in a wrong way

# June 10, 2010 2:35 AM

steva said:

I want to use this code in custom aspx pages in Sharepoint, but I get error message: "Code block are not allowed in this file."

# June 17, 2010 9:23 AM

alaa9jo said:

I have to say that this issue has nothing to do with the library.

Anyway,To get this working you need to modify the web.config of your web application. For instance, if you want to allow server side script on pages from the masterpage & pagelayout gallery you have to modify the PageParserPaths into:

<.pageparserpaths>

<.pageparserpath virtualpath="/_catalogs/masterpage/*" compilationmode="Always" allowserversidescript="true" includesubfolders="true".>

<./pageparserpaths>

# June 17, 2010 10:32 AM

steva said:

The thing is that nothing is changed after I put that code in the web.config....

error message remains "Code blocks are not allowed in this file". I put code between <.script></.script> tags in the PlaceHolderAdditionalPageHead in the custom page, not in the master page.

I think that the problem is in this part "#<%= TextBox1.ClientID %>", is there any other way to write this line?

# June 21, 2010 9:25 AM

alaa9jo said:

I'm not sure if this is the real cause of the issue in SharePoint but yes there is another way to write the line.

Replace:   $('#<%= TextBox1.ClientID%>')

With this: $("input[id$='TextBox1']")

# June 22, 2010 9:43 AM

steva said:

Thank you for help, that was solution for my problem, now everything works fine :)

# June 23, 2010 5:54 AM

LennyPain said:

This is awesome, but can you please describe if it's possible to change the first day of week? I played around a little with the .js code but couldn't get it to work since I suck at javascript/jQuery.

I'm planning to use this on a site where the visitors will be located all over the world and they probably want to have the calendar localized. Weekday names in English are all fine but I need to change first day of week depending on regional settings since they will select weekly data on my site.

# August 14, 2010 6:40 PM

alaa9jo said:

if you want to change the first day of the week WITHOUT localization then its very simple,use the option firstDay in the datepickeroptions:

datepickerOptions: { changeMonth: true, changeYear: true,firstDay:1}

firstDay:1 --> Monday,0:Sunday

# August 16, 2010 3:39 AM

LennyPain said:

So easy! I tried a similar solution but didn't wrap it in a datepickerOptions object. Now it's working like it should!

Thank you for the quick answer.

# August 16, 2010 12:58 PM

Mohan Prajapati said:

Hello friends,

I have tried to implement date range picker control. You can get the code at this link

aspnet-ajax-aspnetmvc.blogspot.com/.../jquery-date-range-plugin.html

Please suggest me to make it more better.

Thanks,

Mohan Prajapati

# September 3, 2010 6:43 AM

LLL said:

A million Thanks!!!!!!!!!!!

# January 27, 2011 10:35 PM

Sandeep said:

Thanks for such a useful contribution, I was wondering if this could be used within a update panel.

Right now asynchronous post back makes it disappear.

# July 8, 2011 2:39 AM

alaa9jo said:

You need to re-run the jquery script after async postback,you can add the script inside pageLoad javascript function,like this:

<script type="text/javascript">

function pageLoad()

{

$(function() {

$("#<%= TextBox1.ClientID%>").attr("readonly","readonly");

$("#<%= TextBox1.ClientID %>").attr("unselectable", "on");

$("#<%= TextBox1.ClientID %>").daterangepicker({ presetRanges: [], arrows: true, dateFormat: 'd M, yy', clearValue: '', datepickerOptions: { changeMonth: true, changeYear: true} });

           });

}

</script>

another option is to run your script once end_Request is called,like this:

<script type="text/javascript">

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(RunThisAfterEachAsync);

function RunThisAfterEachAsync()

{

$("#<%= TextBox1.ClientID%>").attr("readonly","readonly");

$("#<%= TextBox1.ClientID %>").attr("unselectable", "on");

$("#<%= TextBox1.ClientID %>").daterangepicker({ presetRanges: [], arrows: true, dateFormat: 'd M, yy', clearValue: '', datepickerOptions: { changeMonth: true, changeYear: true} });

           });

}

</script>

side note: I wrote the script on a rush but I'm sure it will work fine without any issues,let me know if it worked ;)

# July 9, 2011 3:41 AM

JAY said:

Thank you.  I been fiddling with it trying to work in asp.net. And then come across your article, you made my day.

# July 6, 2012 3:11 PM

Is there a good JS ranged datepicker control out there?Javascript Language Development | Javascript Language Development | Javascript Language Development said:

Pingback from  Is there a good JS ranged datepicker control out there?Javascript Language Development | Javascript Language Development | Javascript Language Development

# March 26, 2013 3:49 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)