In this article I will explain with an example, how to implement
jQuery TimePicker plugin in ASP.Net Core MVC.
Download jQuery TimePicker Plugin
You will need to download the plugin files from the following location.
The complete documentation is available in the following link.
Controller
The Controller consists of following two Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
Action method for handling POST operation
This Action method gets called when the Form is submitted.
Inside this Action Method, the value of the selected Time is fetched and set into a
ViewBag object.
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(string time)
{
DateTime dt = Convert.ToDateTime(time);
ViewBag.Message = dt.ToShortTimeString();
return View();
}
}
View
The View consists of an HTML Form which has been created using the following TagHelpers attributes.
asp-action – Name of the Action. In this case the name is Index.
asp-controller – Name of the Controller. In this case the name is Home.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
Inside the Form, there is an HTML TextBox and a Submit Button.
jQuery TimePicker Plugin implementation
Inside the View, the following
jQuery TimePicker CSS file is inherited.
1. jquery.timepicker.min.css
And then, the following
jQuery and
jQuery TimePicker JS script files are inherited.
1. jquery.min.js
2. jquery.timepicker.min.js
Inside the
jQuery document ready event handler, the HTML TextBox has been applied with the
jQuery TimePicker plugin.
Submitting the Form
When the Time is selected and the
Submit button is clicked, the Form is submitted and the
ViewBag object is checked for NULL and if it is not NULL then, the value of the
ViewBag object is displayed using JavaScript Alert Message Box.
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("[id*=txtTime]").timepicker();
});
</script>
</head>
<body>
<form method="post" asp-controller="Home" asp-action="Index">
<input type="text"id="txtTime" name="time" />
<input type="submit"id="btnSubmit" value="Submit" />
</form>
@if (ViewBag.Message != null)
{
<script type="text/javascript">
window.onload = function () {
alert("@ViewBag.Message");
};
</script>
}
</body>
</html>
Screenshot
Demo
Downloads