ASP.NET MVC 5 - Time Picker Plugin

This article is about integration and basic usage of the Bootstrap Time Picker jQuery plugin in ASP.NET MVC5 platform.

In most of the scenarios, time is usually an auto-generated component of the product but occasionally, there comes a situation where time input is required from the end-user. For such scenarios, there is a very simple and interactive jQuery plugin Bootstrap Time Picker available. This plugin adds interactivity to the end-user choice of providing time input.

Today, I shall be demonstrating integration and basic usage of the Bootstrap Time Picker jQuery plugin in ASP.NET MVC5 platform.

ASP.NET MVC 5 - Time Picker Plugin

Prerequisites

Following are some prerequisites before you proceed any further in this tutorial.

  1. Knowledge of ASP.NET MVC5.
  2. Knowledge of HTML.
  3. Knowledge of JavaScript.
  4. Knowledge of Bootstrap.
  5. Knowledge of Jquery.
  6. Knowledge of C# Programming.

You can download the complete source code for this tutorial or you can follow the step by step discussion below. The sample code is being developed in Microsoft Visual Studio 2017 Professional.

Let's begin now.

Step 1

Create a new MVC web project and name it "MvcTimePicker".  

Step 2

Open the "Views->Shared->_Layout.cshtml" file and replace its content with the following code.

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="utf-8" />  
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">  
  6.     <title>@ViewBag.Title</title>  
  7.     @Styles.Render("~/Content/css")  
  8.     @Scripts.Render("~/bundles/modernizr")  
  9.   
  10.     <!-- Font Awesome -->  
  11.     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />  
  12.   
  13.     <!-- Time Picker -->  
  14.     @Styles.Render("~/Plugin/Timepicker/css")  
  15.   
  16. </head>  
  17. <body>  
  18.     <div class="navbar navbar-inverse navbar-fixed-top">  
  19.         <div class="container">  
  20.             <div class="navbar-header">  
  21.                 <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">  
  22.                     <span class="icon-bar"></span>  
  23.                     <span class="icon-bar"></span>  
  24.                     <span class="icon-bar"></span>  
  25.                 </button>  
  26.             </div>  
  27.         </div>  
  28.     </div>  
  29.     <div class="container body-content">  
  30.         @RenderBody()  
  31.         <hr />  
  32.         <footer>  
  33.             <center>  
  34.                 <p><strong>Copyright © @DateTime.Now.Year - <a href="http://www.asmak9.com/">Asma's Blog</a>.</strong> All rights reserved.</p>  
  35.             </center>  
  36.         </footer>  
  37.     </div>  
  38.   
  39.     @Scripts.Render("~/bundles/jquery")  
  40.     @Scripts.Render("~/bundles/bootstrap")  
  41.   
  42.     <!-- Timepicker -->  
  43.     <script type="text/javascript" src="//cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>  
  44.     @Scripts.Render("~/bundles/Script-Timepicker")  
  45.     @Scripts.Render("~/bundles/Script-Custom-Timepicker")  
  46.   
  47.     @RenderSection("scripts", required: false)  
  48. </body>  
  49. </html> 

In the above code, I have simply created a basic default layout page and linked the required libraries into it.

Step 3

Now, create a new "Models\TimerViewModel.cs" file and replace the following code in it.

  1. //-----------------------------------------------------------------------  
  2. // <copyright file="HTMLDisplayViewModel.cs" company="None">  
  3. //     Copyright (c) Allow to distribute this code and utilize this code for personal or commercial purpose.  
  4. // </copyright>  
  5. // <author>Asma Khalid</author>  
  6. //-----------------------------------------------------------------------  
  7.   
  8. namespace MvcTimerPicker.Models  
  9. {  
  10.     using System.Collections.Generic;  
  11.     using System.ComponentModel.DataAnnotations;  
  12.     using System.Web.Mvc;  
  13.   
  14.     /// <summary>  
  15.     /// Timer view model class.  
  16.     /// </summary>  
  17.     public class TimerViewModel  
  18.     {  
  19.         /// <summary>  
  20.         /// Gets or sets the HTML content property.  
  21.         /// </summary>  
  22.         [Required]  
  23.         [Display(Name = "Time")]  
  24.         public string Timer { getset; }  
  25.   
  26.         /// <summary>  
  27.         /// Gets or sets message property.  
  28.         /// </summary>  
  29.         [Display(Name = "Message")]  
  30.         public string Message { getset; }  
  31.   
  32.         /// <summary>  
  33.         /// Gets or sets a value indicating whether it is valid or not property.  
  34.         /// </summary>  
  35.         [Display(Name = "Is Valid")]  
  36.         public bool IsValid { getset; }  
  37.     }  

In the above code, I have created my View Model which I will attach to my View. Here, I have created a string type Timer property which will capture the time input from the end-user. I have also added message property which will display either success or failure messages from server side and finally, I have added a "is valid" property which will validate the success or failure from the server side to display a proper message.

Step 4

Create a new "Controllers\TimerController.cs" file and replace the following code.

  1. //-----------------------------------------------------------------------  
  2. // <copyright file="TimerController.cs" company="None">  
  3. //     Copyright (c) Allow to distribute this code and utilize this code for personal or commercial purpose.  
  4. // </copyright>  
  5. // <author>Asma Khalid</author>  
  6. //-----------------------------------------------------------------------  
  7.   
  8. namespace MvcTimerPicker.Controllers  
  9. {  
  10.     using System;  
  11.     using System.Collections.Generic;  
  12.     using System.Globalization;  
  13.     using System.Linq;  
  14.     using System.Web;  
  15.     using System.Web.Mvc;  
  16.     using Models;  
  17.   
  18.     /// <summary>  
  19.     /// Timer controller class.  
  20.     /// </summary>  
  21.     public class TimerController : Controller  
  22.     {  
  23.         #region Index view method.  
  24.  
  25.         #region Get: /Timer/Index method.  
  26.   
  27.         /// <summary>  
  28.         /// Get: /Timer/Index method.  
  29.         /// </summary>          
  30.         /// <returns>Return index view</returns>  
  31.         public ActionResult Index()  
  32.         {  
  33.             // Initialization/  
  34.             TimerViewModel model = new TimerViewModel() { Timer = null, IsValid = false, Message = string.Empty };  
  35.   
  36.             try  
  37.             {  
  38.             }  
  39.             catch (Exception ex)  
  40.             {  
  41.                 // Info  
  42.                 Console.Write(ex);  
  43.             }  
  44.   
  45.             // Info.  
  46.             return this.View(model);  
  47.         }  
  48.  
  49.         #endregion  
  50.  
  51.         #region POST: /Timer/Index  
  52.   
  53.         /// <summary>  
  54.         /// POST: /Timer/Index  
  55.         /// </summary>  
  56.         /// <param name="model">Model parameter</param>  
  57.         /// <returns>Return - Response information</returns>  
  58.         [HttpPost]  
  59.         [AllowAnonymous]  
  60.         [ValidateAntiForgeryToken]  
  61.         public ActionResult Index(TimerViewModel model)  
  62.         {  
  63.             try  
  64.             {  
  65.                 // Verification  
  66.                 if (ModelState.IsValid)  
  67.                 {  
  68.                     // Initialization.  
  69.                     string format = "yyyy-MM-dd HH:mm:ss.fff";  
  70.                     string formatDisplay = "hh:mm tt";  
  71.                     DateTime dateTimeVal = Convert.ToDateTime(model.Timer);  
  72.   
  73.                     // Timer Settings.  
  74.                     string timerVal = dateTimeVal != null ? dateTimeVal.ToString(format, CultureInfo.InvariantCulture) : dateTimeVal.ToString();  
  75.                     string timerDisplay = dateTimeVal != null ? dateTimeVal.ToString(formatDisplay, CultureInfo.InvariantCulture) : dateTimeVal.ToString();  
  76.   
  77.                     // Settings.  
  78.                     ModelState.Clear();  
  79.                     model.Timer = timerVal;  
  80.                     model.Message = timerDisplay + " timer has been Set successfully!!";  
  81.                     model.IsValid = true;  
  82.                 }                  
  83.             }  
  84.             catch (Exception ex)  
  85.             {  
  86.                 // Info  
  87.                 Console.Write(ex);  
  88.             }  
  89.   
  90.             // Info  
  91.             return this.View(model);  
  92.         }  
  93.  
  94.         #endregion  
  95.  
  96.         #endregion  
  97.     }  

In the above code, I have created GET "Index(...)" method and POST "Index(...)" methods where I will receive the input of the timer from the end-user, and after applying the standard date/time format for the storage purpose, I have sent the required success message to the View page.

Step 5

Now, create a view "Views\Timer\Index.cshtml" file and replace the following code in it..

  1. @using MvcTimerPicker.Models  
  2. @model TimerViewModel  
  3. @{  
  4.     ViewBag.Title = "ASP.NET MVC5: Time Picker Plugin";  
  5. }  
  6.   
  7. <div class="row">  
  8.     <div class="panel-heading">  
  9.         <div class="col-md-8">  
  10.             <h3>  
  11.                 <i class="fa fa-clock-o"></i>  
  12.                 <span>ASP.NET MVC5: Time Picker Plugin</span>  
  13.             </h3>  
  14.         </div>  
  15.     </div>  
  16. </div>  
  17.   
  18. <br />  
  19.   
  20. <h5>  
  21.     <i class="fa fa-link" aria-hidden="true"></i>  
  22.     <a href="https://jdewit.github.io/bootstrap-timepicker/">Bootstrap Time Picker</a>  
  23. </h5>  
  24.   
  25. <hr />  
  26.   
  27. <div class="row">  
  28.     <div class="col-md-12 col-md-push-1">  
  29.         <section>  
  30.             @using (Html.BeginForm("Index", "Timer", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal"role = "form" }))  
  31.             {  
  32.                 @Html.AntiForgeryToken()  
  33.   
  34.                 <div class="row" style="display:none;">  
  35.                     <div class="form-group">  
  36.                         <div class="col-md-10">  
  37.                             @Html.HiddenFor(m => m.Timer, new { id = "timerValId", @readonly = "readonly"placeholder = Html.DisplayNameFor(m => m.Timer), @class = "form-control" })  
  38.                         </div>  
  39.                     </div>  
  40.                 </div>  
  41.   
  42.                 <div class="form-group">  
  43.                     <div class="row">  
  44.                         <div class="col-md-4">  
  45.                             <div class="input-group">  
  46.                                 <span class="input-group-addon">Time</span>  
  47.                                 <input id="timerId" type='text' class="form-control text-center" placeholder="Time" readonly="readonly" />  
  48.                                 <span class="input-group-addon">  
  49.                                     <span class="fa fa-clock-o"></span>  
  50.                                 </span>  
  51.                             </div>  
  52.   
  53.                             @if (Model.IsValid && !string.IsNullOrEmpty(Model.Message))  
  54.                             {  
  55.                                 <span class="text-success">@Model.Message</span>  
  56.                             }  
  57.                             else  
  58.                             {  
  59.                                 <span class="text-danger">@Model.Message</span>  
  60.                                 @Html.ValidationMessageFor(m => m.Timer, "", new { @class = "text-danger" })  
  61.                             }  
  62.                         </div>  
  63.   
  64.                         <div class="col-md-4">  
  65.                             <input type="submit" value="Set" class="btn btn-info" />  
  66.                         </div>  
  67.                     </div>  
  68.                 </div>  
  69.             }  
  70.         </section>  
  71.     </div>  
  72. </div> 

In the above code, I have created a simple View for taking time input from the end-user via Bootstrap Time Picker jQuery plugin.

Step 6

Create "Scripts\script-custom-timepicker.js" file and replace following code in it.

  1. $(document).ready(function ()  
  2. {  
  3.     var timerVal = moment().format('hh:mm A');  
  4.   
  5.     // Verification  
  6.     if ($('#timerValId').data() &&  
  7.         $('#timerValId').val() != null &&  
  8.         $('#timerValId').val() != '')  
  9.     {  
  10.         timerVal = moment($('#timerValId').val()).format('hh:mm A');  
  11.     }  
  12.     else if ($('#timerValId').data() &&  
  13.         ($('#timerValId').val() == null ||  
  14.         $('#timerValId').val() == ''))  
  15.     {  
  16.         $('#timerValId').val(timerVal);  
  17.     }  
  18.   
  19.     $('#timerId').timepicker(  
  20.         {  
  21.             template: 'dropdown',  
  22.             minuteStep: 1,  
  23.             secondStep: 1,  
  24.             showMeridian: true,  
  25.             defaultTime: timerVal  
  26.         });  
  27.   
  28.     $('#timerId').timepicker().on('hide.timepicker'function (e)  
  29.     {  
  30.         console.log('The time is ' + e.time.value);  
  31.   
  32.         $('#timerValId').val(e.time.value);  
  33.     });  
  34. }); 

In the above code, I have created basic Bootstrap Time Picker jQuery plugin settings to integrate the plugin with ASP.NET MVC platform. At first, I am verifying whether the current input value is empty or not, then I set the value accordingly, and finally, I have attached the time picker plugin with my UI and update its value as the timer plugin is closed.

Step 7

Now, execute the project and you will be able to see the following in action.

ASP.NET MVC 5 - Time Picker Plugin

ASP.NET MVC 5 - Time Picker Plugin

Conclusion

In this article, we learned how to integrate Bootstrap Time Picker jQuery plugin with ASP.NET MVC5 platform. Also, we looked into the basic usage of the time picker plugin and learned to take time input from end-user and apply proper date/time format to the provided time input.