More DatePickers!

In continuation of my previous post on jQuery UI, I updated the project on CodePlex with a demo of how multiple date pickers can be included. It’s very simple, just requires a little bit of nifty JavaScript. In fact, it’s a one-liner.


Yep! That simple. This will activate the date picker on every element whose id has "date"-something in it. Like so:

@Html.TextBoxFor(model => model.DateTime1, new { id = "date1" })
@Html.TextBoxFor(model => model.DateTime2, new { id = "date2" })

Here’s a screenshot of how that looks:

Get the project from CodePlex and play around. I will be updating it soon again.

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() {

Now in the form that contains the date fields:

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

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.


Get every new post delivered to your Inbox.

Join 256 other followers