Header Ads

ASP.NET MVC5: Time Picker Plugin

In most of the scenarios, time is usually 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 plugins 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.


Prerequisites:

Following are some prerequisites before you proceed any further in this tutorial:
  1. Download Bootstrap Time Picker JQuery Plugin.
  2. Knowledge of ASP.NET MVC5.
  3. Knowledge of HTML.
  4. Knowledge of JavaScript.
  5. Knowledge of Bootstrap.
  6. Knowledge of Jquery.
  7. 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.

Download Link

Let's begin now.

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

2) Open the "Views->Shared->_Layout.cshtml" file and replace following code in it i.e.

<!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")

    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />

    <!-- Time Picker -->
    @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 &copy; @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")

    <!-- Timepicker -->
    <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 require libraries into it.

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

//-----------------------------------------------------------------------
// <copyright file="HTMLDisplayViewModel.cs" company="None">
//     Copyright (c) Allow to distribute this code and utilize this code for personal or commercial purpose.
// </copyright>
// <author>Asma Khalid</author>
//-----------------------------------------------------------------------

namespace MvcTimerPicker.Models
{
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Web.Mvc;

    /// <summary>
    /// Timer view model class.
    /// </summary>
    public class TimerViewModel
    {
        /// <summary>
        /// Gets or sets the HTML content property.
        /// </summary>
        [Required]
        [Display(Name = "Time")]
        public string Timer { get; set; }

        /// <summary>
        /// Gets or sets message property.
        /// </summary>
        [Display(Name = "Message")]
        public string Message { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether it is valid or not property.
        /// </summary>
        [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 string type Timer property which will capture time input from the end-user. I have also added message property which will display either success or failure messages from the server side and finally, I have added is valid property which will validate success or failure from server side to display proper message.

4) Create a new "Controllers\TimerController.cs" file and replace the following code in it i.e.

//-----------------------------------------------------------------------
// <copyright file="TimerController.cs" company="None">
//     Copyright (c) Allow to distribute this code and utilize this code for personal or commercial purpose.
// </copyright>
// <author>Asma Khalid</author>
//-----------------------------------------------------------------------

namespace MvcTimerPicker.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using Models;

    /// <summary>
    /// Timer controller class.
    /// </summary>
    public class TimerController : Controller
    {
        #region Index view method.

        #region Get: /Timer/Index method.

        /// <summary>
        /// Get: /Timer/Index method.
        /// </summary>        
        /// <returns>Return index view</returns>
        public ActionResult Index()
        {
            // Initialization/
            TimerViewModel model = new TimerViewModel() { Timer = null, IsValid = false, Message = string.Empty };

            try
            {
            }
            catch (Exception ex)
            {
                // Info
                Console.Write(ex);
            }

            // Info.
            return this.View(model);
        }

        #endregion

        #region POST: /Timer/Index

        /// <summary>
        /// POST: /Timer/Index
        /// </summary>
        /// <param name="model">Model parameter</param>
        /// <returns>Return - Response information</returns>
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Index(TimerViewModel model)
        {
            try
            {
                // Verification
                if (ModelState.IsValid)
                {
                    // Initialization.
                    string format = "yyyy-MM-dd HH:mm:ss.fff";
                    string formatDisplay = "hh:mm tt";
                    DateTime dateTimeVal = Convert.ToDateTime(model.Timer);

                    // Timer Settings.
                    string timerVal = dateTimeVal != null ? dateTimeVal.ToString(format, CultureInfo.InvariantCulture) : dateTimeVal.ToString();
                    string timerDisplay = dateTimeVal != null ? dateTimeVal.ToString(formatDisplay, CultureInfo.InvariantCulture) : dateTimeVal.ToString();

                    // Settings.
                    ModelState.Clear();
                    model.Timer = timerVal;
                    model.Message = timerDisplay + " timer has been Set successfully!!";
                    model.IsValid = true;
                }                
            }
            catch (Exception ex)
            {
                // Info
                Console.Write(ex);
            }

            // Info
            return this.View(model);
        }

        #endregion

        #endregion
    }
}

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

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

@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.

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

$(document).ready(function ()
{
    var timerVal = moment().format('hh:mm A');

    // Verification
    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 that whether 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.

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


Conclusion

In this article, you will learn to integrate Bootstrap Time Picker JQuery plugin with ASP.NET MVC5 platform. You will also learn about the basic usage of the time picker plugin and also learn to take time input from end-user and apply proper date/time format to the provided time input.

No comments