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.
- Knowledge of ASP.NET MVC5.
- Knowledge of HTML.
- Knowledge of JavaScript.
- Knowledge of Bootstrap.
- Knowledge of Jquery.
- 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.
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>@ViewBag.Title</title>
- @Styles.Render("~/Content/css")
- @Scripts.Render("~/bundles/modernizr")
-
-
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />
-
-
- @Styles.Render("~/Plugin/Timepicker/css")
-
- </head>
- <body>
- <div class="navbar navbar-inverse navbar-fixed-top">
- <div class="container">
- <div class="navbar-header">
- <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- </button>
- </div>
- </div>
- </div>
- <div class="container body-content">
- @RenderBody()
- <hr />
- <footer>
- <center>
- <p><strong>Copyright © @DateTime.Now.Year - <a href="http://www.asmak9.com/">Asma's Blog</a>.</strong> All rights reserved.</p>
- </center>
- </footer>
- </div>
-
- @Scripts.Render("~/bundles/jquery")
- @Scripts.Render("~/bundles/bootstrap")
-
-
- <script type="text/javascript" src="//cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
- @Scripts.Render("~/bundles/Script-Timepicker")
- @Scripts.Render("~/bundles/Script-Custom-Timepicker")
-
- @RenderSection("scripts", required: false)
- </body>
- </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.
-
-
-
-
-
-
-
- namespace MvcTimerPicker.Models
- {
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Web.Mvc;
-
-
-
-
- public class TimerViewModel
- {
-
-
-
- [Required]
- [Display(Name = "Time")]
- public string Timer { get; set; }
-
-
-
-
- [Display(Name = "Message")]
- public string Message { get; set; }
-
-
-
-
- [Display(Name = "Is Valid")]
- public bool IsValid { get; set; }
- }
- }
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.
-
-
-
-
-
-
-
- namespace MvcTimerPicker.Controllers
- {
- using System;
- using System.Collections.Generic;
- using System.Globalization;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using Models;
-
-
-
-
- public class TimerController : Controller
- {
- #region Index view method.
-
- #region Get: /Timer/Index method.
-
-
-
-
-
- public ActionResult Index()
- {
-
- TimerViewModel model = new TimerViewModel() { Timer = null, IsValid = false, Message = string.Empty };
-
- try
- {
- }
- catch (Exception ex)
- {
-
- Console.Write(ex);
- }
-
-
- return this.View(model);
- }
-
- #endregion
-
- #region POST: /Timer/Index
-
-
-
-
-
-
- [HttpPost]
- [AllowAnonymous]
- [ValidateAntiForgeryToken]
- public ActionResult Index(TimerViewModel model)
- {
- try
- {
-
- if (ModelState.IsValid)
- {
-
- string format = "yyyy-MM-dd HH:mm:ss.fff";
- string formatDisplay = "hh:mm tt";
- DateTime dateTimeVal = Convert.ToDateTime(model.Timer);
-
-
- string timerVal = dateTimeVal != null ? dateTimeVal.ToString(format, CultureInfo.InvariantCulture) : dateTimeVal.ToString();
- string timerDisplay = dateTimeVal != null ? dateTimeVal.ToString(formatDisplay, CultureInfo.InvariantCulture) : dateTimeVal.ToString();
-
-
- ModelState.Clear();
- model.Timer = timerVal;
- model.Message = timerDisplay + " timer has been Set successfully!!";
- model.IsValid = true;
- }
- }
- catch (Exception ex)
- {
-
- Console.Write(ex);
- }
-
-
- return this.View(model);
- }
-
- #endregion
-
- #endregion
- }
- }
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..
- @using MvcTimerPicker.Models
- @model TimerViewModel
- @{
- ViewBag.Title = "ASP.NET MVC5: Time Picker Plugin";
- }
-
- <div class="row">
- <div class="panel-heading">
- <div class="col-md-8">
- <h3>
- <i class="fa fa-clock-o"></i>
- <span>ASP.NET MVC5: Time Picker Plugin</span>
- </h3>
- </div>
- </div>
- </div>
-
- <br />
-
- <h5>
- <i class="fa fa-link" aria-hidden="true"></i>
- <a href="https://jdewit.github.io/bootstrap-timepicker/">Bootstrap Time Picker</a>
- </h5>
-
- <hr />
-
- <div class="row">
- <div class="col-md-12 col-md-push-1">
- <section>
- @using (Html.BeginForm("Index", "Timer", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
- {
- @Html.AntiForgeryToken()
-
- <div class="row" style="display:none;">
- <div class="form-group">
- <div class="col-md-10">
- @Html.HiddenFor(m => m.Timer, new { id = "timerValId", @readonly = "readonly", placeholder = Html.DisplayNameFor(m => m.Timer), @class = "form-control" })
- </div>
- </div>
- </div>
-
- <div class="form-group">
- <div class="row">
- <div class="col-md-4">
- <div class="input-group">
- <span class="input-group-addon">Time</span>
- <input id="timerId" type='text' class="form-control text-center" placeholder="Time" readonly="readonly" />
- <span class="input-group-addon">
- <span class="fa fa-clock-o"></span>
- </span>
- </div>
-
- @if (Model.IsValid && !string.IsNullOrEmpty(Model.Message))
- {
- <span class="text-success">@Model.Message</span>
- }
- else
- {
- <span class="text-danger">@Model.Message</span>
- @Html.ValidationMessageFor(m => m.Timer, "", new { @class = "text-danger" })
- }
- </div>
-
- <div class="col-md-4">
- <input type="submit" value="Set" class="btn btn-info" />
- </div>
- </div>
- </div>
- }
- </section>
- </div>
- </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.
- $(document).ready(function ()
- {
- var timerVal = moment().format('hh:mm A');
-
-
- if ($('#timerValId').data() &&
- $('#timerValId').val() != null &&
- $('#timerValId').val() != '')
- {
- timerVal = moment($('#timerValId').val()).format('hh:mm A');
- }
- else if ($('#timerValId').data() &&
- ($('#timerValId').val() == null ||
- $('#timerValId').val() == ''))
- {
- $('#timerValId').val(timerVal);
- }
-
- $('#timerId').timepicker(
- {
- template: 'dropdown',
- minuteStep: 1,
- secondStep: 1,
- showMeridian: true,
- defaultTime: timerVal
- });
-
- $('#timerId').timepicker().on('hide.timepicker', function (e)
- {
- console.log('The time is ' + e.time.value);
-
- $('#timerValId').val(e.time.value);
- });
- });
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.
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.