jQuery UI Date picker Popup Calendar in MVC application

This article walks through the process of adding jQuery UI date picker popup calendar to the HTML text box control.

After MVC 4 web application template is chosen and Internet Application is selected from the available templates Visual Studio generates all the files(Models, views, Controllers, Scripts etc.,) that are required to implement MVC Web application.

Open the BundleConfig.cs from App_Start folder, there are 6 jQuery and CSS bundles are processed (shown below).

image 

Open the _Layout.cshtml from Views --> Shared folder, there are only 3 bundles are being used on views(Not 6 bundles) as shown below.

image

In order to get the date picker it is required to add two more references on the view where datepicker is required to render.

Follow below steps:-

1. Add below jQuery to a new javascript file in Scripts folder.

   1: $(function () {
   2:             $("#Text1").datepicker({
   3:                 changeMonth: true,
   4:                 changeYear: true
   5:             });
   6:         });

jQuery function is self-explanatory. jQuery function selects the text box control where id is Text1 and adds the datepicker function with required properties set to True.

2. Add below section to the view where datepicker should be rendered.

   1: @section Scripts{
   2:     @Scripts.Render("~/bundles/jqueryval")
   3:  
   4:     @Scripts.Render("~/bundles/jqueryui")
   5:     @Scripts.Render("~/Scripts/DatePicker.js");
   6:     
   7: }

Adding the above script renders date picker when the textbox is selected as shown below.

image

3. CSS - Style

Date picker look and feel is NOT good at the moment. Lets add a theme from the CDN(Content Delivery Network)http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.17/themes/dot-luv/jquery-ui.css.

Now the date picker looks better as shown below.

image

Below is the amended section that is added to the view where date picker to be rendered.

   1: @section Scripts{
   2:  
   3:     @Scripts.Render("~/bundles/jqueryval")
   4:  
   5:     @Scripts.Render("~/bundles/jqueryui")
   6:     @Scripts.Render("~/Scripts/DatePicker.js");
   7: @Styles.Render("http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.17/themes/dot-luv/jquery-ui.css");
   8:   
   9: }

Summary:-
Note that above solution can suffice for pages. The best practice is to implement application level solution that can render packer when the textbox is of type Date.

Refer Using the HTML5 and jQuery UI Datepicker Popup Calendar with ASP.NET MVC for step by step guidance.

No Comments