ASP.Net MVC DatePicker

Play this article

I recently worked on a project that had a big form with a lot of date fields. I generally believe it is good practise to show the user a calendar when they either click in the date field or on a calendar icon next to the field.

jQuery UI’s Datepicker does a very good job at making this easy. All I had to do is add a class to the text boxes i would like to use as datepickers:

@Html.TextBoxFor(model => model.DoB, new { @class = "datepicker" })

And add a piece of Javascript to add a datepicker to all the elements which has a class datepicker:

    showOn: "both",
    buttonImage: "../public/images/Calendar_16x16.png",
    buttonImageOnly: "true"

Also, you need to make sure that you have referenced the jQuery and jQuery UI libraries in order for this to work.

If all goes well you should have an attractive icon next to your date field. Setting the showOn parameter to both, will show the date picker when the textbox has focus or when the user clicks on the icon next to the textbox.


With ASP.Net MVC this could even be easier. By creating a helper, we do not have to manually specify the class name every time we need a date picker text box. The code for the helper would look like this:

@helper DatePicker(string name, object value = null)
        var val = value  "";
        <input type="text" name="@name" class="datepicker" id="@name" value="@val" />

Using it in your view would then look like this:


Just make sure, you have the Javascript in either your _Layout or the page in order for the jQueryUI date picker to work.