Datepicker In MVC 4

  • jquery.ui.core.js
  • jquery.ui.core.min.js
  • jquery.ui.datepicker.js
  • jquery.ui.datepicker.min.js
  1. $(function ()  
  2. { $(".datefield").datepicker();  
  3. });  
To actually use the jQuery date picker, you need to create a jQuery script that will hook up the calendar widget to the edit template. In Solution Explorer, right-click the Scripts folder and selectAdd, then New Item, and then JScript File. Name the file DatePickerReady.js.

Open the Views\Shared\_Layout.cshtml file. You need to add references to the following files, which are all required so that you can use the date picker:

  • Content/themes/base/jquery.ui.core.css
  • Content/themes/base/jquery.ui.datepicker.css
  • Content/themes/base/jquery.ui.theme.css
  • jquery.ui.core.min.js
  • jquery.ui.datepicker.min.js
  • DatePickerReady.js
The following example shows the actual code that you should add at the bottom of the head element in the Views\Shared\_Layout.cshtml file.
  1. <link href="@Url.Content("~/Content/themes/base/jquery.ui.core.css")" rel="stylesheet" type="text/css"/>  
  2. <link href="@Url.Content("~/Content/themes/base/jquery.ui.datepicker.css")" rel="stylesheet type="text/css" />  
  3. <link href="@Url.Content("~/Content/themes/base/jquery.ui.theme.css")" rel="stylesheet" type="text/css"/>  
  4. <script src="@Url.Content("~/Scripts/jquery.ui.core.min.js")" type="text/javascript"></script>  
  5. <script src="@Url.Content("~/Scripts/jquery.ui.datepicker.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/DatePickerReady.js")" type="text/javascript"></script>  

Supporting the HTML5 Date Input Control

As more browsers support HTML5, you'll want to use the native HTML5 input, such as the date input element, and not use the jQuery UI calendar. You can add logic to your application to automatically use HTML5 controls if the browser supports them. To do this, replace the contents of the DatePickerReady.js file with the following.

  1. if (!Modernizr.inputtypes.date) {  
  2.     $(function() {  
  3.         $(".datefield").datepicker();  
  4.     });  
  5. }  
The first line of this script uses Modernizr to verify if the HTML5 date input is supported. If it's not supported, the jQuery UI date picker is hooked up instead. (Modernizr is an open-source JavaScript library that detects the availability of native implementations of HTML5 and CSS3.) Modernizr is included in any new ASP.NET MVC projects that you create.