Multiple Datepickers

Using ASP.NET MVC with Javascript is like a breeze and really quite useful too. I needed to have several date fields in a form for the project I am currently working on. I found jQuery UI to be a great and very pretty solution and thought I might share.

First I got the jQuery UI and placed it in the Content folder of the MVC project. I had put my script in a file called datepicker.js also in the Content folder. They can be anywhere else too, depending on that the following paths will have to be changed. Furthermore the jQuery JavaScript library will also be needed. It’s already there in the MVC project’s Scripts and jQuery UI’s js folder.

Referring to them all:

<link type="text/css" href="<%= Url.Content("~/Content/jqueryUI/css/smoothness/jquery-ui-1.7.2.custom.css") %>" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="<%= Url.Content("~/Script/jquery-1.3.2.min.js") %>"></script>
<script type="text/javascript" src="<%= Url.Content("~/Content/jqueryUI/js/jquery-ui-1.7.2.custom.min.js") %>"></script>
<script src="<%= Url.Content("~/Content/datepicker.js") %>" type="text/javascript"></script>

I placed a wildcard in the datepicker function to pick up any element with date in its id:

$(function() {
$("*[id*=date]").datepicker();
});

Now in the form that contains the date fields:

            <p>
                <label for="DateStarted">Date Started:</label>
                <%= Html.TextBox("DateStarted", String.Format("{0:d}", Model.DateStarted), new { @id = "date1" })%>
                <%= Html.ValidationMessage("DateStarted", "*") %>
            </p>
            <p>
                <label for="TerminationDate">Termination Date:</label>
                <%= Html.TextBox("TerminationDate", String.Format("{0:d}", Model.TerminationDate), new { @id = "date2" })%>
                <%= Html.ValidationMessage("TerminationDate", "*") %>
            </p>

I added the id attribute to each text box that was meant as a date field. It’s important to specify date1 and date2 (in lines 3 and 8) or other unique names containing date because the wildcard would cause any name with date in it to register as elements for the datepicker to be applied on.

Hope it will be useful for someone, it surely was for me.

Advertisements