Click here to Skip to main content
Click here to Skip to main content

JQueryUI Datepicker in ASP.NET MVC

, 30 Oct 2011
Rate this:
Please Sign up or sign in to vote.
Using Datepicker JQuery plugin in ASP.NET MVC

Datepicker is a nice and cool plugin for displaying the calendar with ease. It is very easy to use JQuery plugin, it comes as part of JQueryUI library, so if you want to use this – first download JQueryUI from http://jqueryui.com/download and also download JQuery(http://docs.jquery.com/Downloading_jQuery) if you haven’t done so yet.

For example, if you have a form like the one below:

<% using(Html.BeginForm()){%>
  <fieldset>
    <legend>Event Information</legend>
     <p>
        <label for="EventName">Event Name:</label>
        <%= Html.TextBox("EventName")%>
            </p>
            <p>
            <label for="StartDate">Start Date:</label>
            <%= Html.TextBox("StartDate")%>
            </p>
            <p>
            <label for="EndDate">End Date:</label>
            <%= Html.TextBox("EndDate")%>
            </p>
            <p>
                <input type="submit" value="Save" />
            </p>
  </fieldset>
<% }%>

and you want to attach datepicker to “StartDate” and “EndDate” input fields, what you need to do is call the datepicker function on the these input field selectors like below:

<script language="javascript">
    $(document).ready(function() {
    $('#StartDate').datepicker();
    $('#EndDate').datepicker();
    });
</script>

This works fine as we expected. 

Difference in Date format patterns

Consider a scenario where your MVC application supports localization, then the selected date displayed in the input fields also should display in the same date format of the current culture(This format could be custom one or default one). This leads to another issue – Datepicker plugin given by the JQueryUI supports different date formats, but it is different from the one that is available in .NET. For e.g. in order to display a long day name (“Thursday”), .NET uses “dddd” it's equivalent in Datepicker is “DD”.

In order to solve this disparity between the .NET world and Datepicker world, I have created an HTML helper function, which could generate the Datepicker format from a .NET date format.

/// <span class="code-SummaryComment"><summary>
</span>/// JQuery UI DatePicker helper.
/// <span class="code-SummaryComment"></summary>
</span>public static class JQueryUIDatePickerHelper
{
    /// <span class="code-SummaryComment"><summary>
</span>    /// Converts the .net supported date format current culture 
    /// format into JQuery Datepicker format.
    /// <span class="code-SummaryComment"></summary>
</span>    /// <span class="code-SummaryComment"><param name="html">HtmlHelper object.</param>
</span>    /// <span class="code-SummaryComment"><returns>Format string that supported in JQuery Datepicker.</returns>
</span>    public static string ConvertDateFormat(this HtmlHelper html)
    {
        return ConvertDateFormat(html, 
	Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern);
    }

    /// <span class="code-SummaryComment"><summary>
</span>    /// Converts the .net supported date format current culture 
    /// format into JQuery Datepicker format.
    /// <span class="code-SummaryComment"></summary>
</span>    /// <span class="code-SummaryComment"><param name="html">HtmlHelper object.</param>
</span>    /// <span class="code-SummaryComment"><param name="format">Date format supported by .NET.</param>
</span>    /// <span class="code-SummaryComment"><returns>Format string that supported in JQuery Datepicker.</returns>
</span>    public static string ConvertDateFormat(this HtmlHelper html, string format)
    {
        /*
         *  Date used in this comment : 5th - Nov - 2009 (Thursday)
         *
         *  .NET    JQueryUI        Output      Comment
         *  --------------------------------------------------------------
         *  d       d               5           day of month(No leading zero)
         *  dd      dd              05          day of month(two digit)
         *  ddd     D               Thu         day short name
         *  dddd    DD              Thursday    day long name
         *  M       m               11          month of year(No leading zero)
         *  MM      mm              11          month of year(two digit)
         *  MMM     M               Nov         month name short
         *  MMMM    MM              November    month name long.
         *  yy      y               09          Year(two digit)
         *  yyyy    yy              2009        Year(four digit)             *
         */

        string currentFormat = format;

        // Convert the date
        currentFormat = currentFormat.Replace("dddd", "DD");
        currentFormat = currentFormat.Replace("ddd", "D");

        // Convert month
        if (currentFormat.Contains("MMMM"))
        {
            currentFormat = currentFormat.Replace("MMMM", "MM");
        }
        else if (currentFormat.Contains("MMM"))
        {
            currentFormat = currentFormat.Replace("MMM", "M");
        }
        else if (currentFormat.Contains("MM"))
        {
            currentFormat = currentFormat.Replace("MM", "mm");
        }
        else
        {
            currentFormat = currentFormat.Replace("M", "m");
        }

        // Convert year
        currentFormat = currentFormat.Contains("yyyy") ? 
	currentFormat.Replace("yyyy", "yy") : currentFormat.Replace("yy", "y");

        return currentFormat;
    }
}

So how could we make use of this helper method? Just replace the datepicker initialization code we have written earlier with this:

<script language="javascript">
    $(document).ready(function() {
    $('#StartDate').datepicker({ dateFormat: '<%= Html.ConvertDateFormat() %>' });
    $('#EndDate').datepicker({ dateFormat: '<%= Html.ConvertDateFormat() %>' });
    });
</script>

Hope this helps.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Rajeesh.C.V
Technical Lead
India India
I am someone who is passionate about programming. I started my career with classic asp and VB 6, later dived into the world of .NET. My ambition is to become a technical architect who could design complex systems in a simplistic form which obeys the "Laws of nature"
 
My personal blog
Follow on   Twitter

Comments and Discussions

 
SuggestionJQuery UI Datepicker Popup Calendar with ASP.NET MVC 5 PinmemberMember 1072790629-Apr-14 1:53 
Questionshows error when we convert yy to yyyy PinmemberPreetika parolkar30-Mar-14 19:45 
GeneralMy vote of 1 Pinprofessionalshabarinadh.vempati3-Dec-13 20:09 
GeneralMy vote of 4 PinmemberPie and Ale16-Jul-13 4:19 
Generalnice article PinmemberDonsw1-Sep-12 8:10 
SuggestionA little suggestion PinmemberDaniele Fusi1-Nov-11 9:19 
GeneralMy vote of 5 Pinmemberkiran dangar31-Oct-11 2:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 31 Oct 2011
Article Copyright 2010 by Rajeesh.C.V
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid