Use a Custom Template in MVC to Automatically Create Datepicker Text Boxes

I started out on this challenge trying to find a way to automatically setup a jQuery datepicker on each rendered text box that had or needed to contain a date. I wanted to keep the standard Html.EditorFor in the MVC View without having to add special instructions to render the required text box that turned it into a datepicker. This is where the MVC Custom Templates come in.

The standard template for a datetime object is the String template. I wanted to create a DateTime template that would create all the necessary information for the jQuery datepicker.

In the Views, Shard folder, create an EditorTemplates folder.

In the EditorTemplates folder, Create a razor page called DateTime.cshtml

I’m using the ContosoUniversity project for the demo as shown below.



Replace the contents of the file with the following code:

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue,
                    new { @class = "text-box single-line", 
                            data_datepicker = "true" })

This will create our TextBox with a data- attribute we can use to hook up the datepicker.

Now, when we load an editor for a model with a DateTime object, MVC will find the DateTime custom template and use that instead of the default String template.

Before it magically appears on every page, we need to get jQuery to attach the datepicker to the new text boxes. We need to include a piece of javascript to do that. I added this line to the contoso.js file that I have in the standard bundle loaded on every page.


An example of editing a student record with an enrollment date is shown below. We haven’t had to modify anything in the view to get this functionality.

Date Picker
Date Picker

The view still looks like this:

        <div class="editor-label">
            @Html.LabelFor(model => model.EnrollmentDate)
        <div class="editor-field">
            @Html.EditorFor(model => model.EnrollmentDate)
            @Html.ValidationMessageFor(model => model.EnrollmentDate)

The work here did lead me on to another post which I should write up now while I’m thinking about it. That is the use of the datepicker when used with localisation.

Leave a Reply

Your email address will not be published. Required fields are marked *