Adding a JQuery datetimepicker to ASP .NET Core 2.1

1 minute read

.NET Core does not include an easy-to-use date/time selection interface. In Rally, I incorporated jquery-datetimepicker, a more visually attractive and intuitive interface. With Visual Studio’s transition of its client-side library manager away from Bower, integrating this library into the project was non-trivial.

JQuery datetimepicker

Install datetimepicker with LibMan

  • Right-click the project in the Solution Explorer. Select Add > Client-Side Library.
  • Make sure the “Provider” is cdnjs.
  • Search for “jquery-datetimepicker”.
  • Select Include all library files.
  • Click Install.

Install moment with LibMan

  • Right-click the project in the Solution Explorer. Select Add > Client-Side Library.
  • Make sure the “Provider” is cdnjs.
  • Search for “moment.js”.
  • Select Choose specific files.
  • Select only the following files:
    • moment.js
    • moment.min.js

Include CSS and JS References in _Layout.cshtml

  • In the <head> section, within <environment include="development">, add the following style sheet reference:
    <link rel="stylesheet" href="~/lib/jquery-datetimepicker/jquery.datetimepicker.css" />
    
  • Before the closing body tag, </body>, within <environment include="development">, add the following script references after any references to jquery.js:
    <script src="~/lib/jquery-datetimepicker/jquery.datetimepicker.js" type="text/javascript"></script>
    <script src="~/lib/moment.js/moment.js"></script>
    <script src="~/js/DateTimePickerReady.js" type="text/javascript"></script>
    

Create JS to Add the datetimepicker

  • Create a file wwwroot/js/DateTimePickerReady.js that contains the following function:
    $(function () {
      $.datetimepicker.setDateFormatter('moment');
      $(".datetimefield").datetimepicker({
          format: 'MM/DD/YYYY hh:mm A',
          formatTime: 'h:mm A'
      });
    });
    

Create An EditorTemplate

  • Create a view Views/Shared/EditorTemplates/DateTime.cshtml that contains the following Razor code:
    @model DateTime
    @Html.TextBox("", Model.ToString("MM/dd/yyyy hh:mm tt"),
    new { @class = "form-control datetimefield", type = "text", autocomplete="off"})
    

Use Razor Syntax in Razor Code

@Html.EditorFor(e => e.StartDate)

Versions and Credits

  • .NET Core 2.1
  • jquery-datetimepicker@2.5.20
  • moment.js@2.22.2