Friday, 22 December 2017

DatePicker or Calendar Control in ASP.NET MVC using jQuery UI

In this tutorial, I am going to explain you how to attach DatePicker or Calendar control in ASP.NET MVC using jQuery UI. I will be using Visual Studio 2013. Below is step by step tutorial.

Creating ASP.NET MVC Empty Application

Now the next step is to create ASP.NET MVC empty application as shown below.
Go to FileNewProject. A new window will be open as shown below.
Now go to Web and select .NET Framework 4.5 and give project name and click on OK .

Creating asp.net mvc 5 application

Now new window will open as shown below.
Now Select Empty Template, check on MVC checkbox and click on OK.

Selecting asp.net mvc 5 empty template

Now, a new project will be created as shown below.

Asp.net mvc 5 empty folder structure

Installing jQuery UI using Nuget (Compulsory)

Next step is to install jQuery.UI. Right click on References and go to Manage NuGet Packages as shown below.

Manage NuGet Packages in ASP.NET MVC

After that a new window will open as shown below. Search for jQuery.UI and install it.

Installing jQuery.UI in ASP.Net Mvc

After successful installation, you can see all css files related to datepicker are installed inside Content folder and and jquery-ui file is installed inside Scripts folder.

After successfull installation of jQuery.UI in ASP.Net Mvc

Installing Bootstrap and Unobtrusive jQuery (Optional)

If bootstrap js,css and Unobtrusive jQuery is not install in your application then you can install using nuget package manager.
Bootstrap: It is used for CSS and responsive design.
Unobtrusive jQuery: It is to make data annotation work at client machine.

Installing Bootstrap and Unobtrusive jQuery in ASP.Net Mvc

Adding Models

Go to Models folder and add new class file Employee.cs. Now replace all code with below code.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace WebApplication1.Models
{
    public class Employee
    {
        [Required]
        [Display(Name = "Date Of Birth")]
        public string DOB { get; set; }
    }
}

Adding Controller

Next step is to add controller to application. Go to controller folder and add new empty controller named as Home controller. Replace all code with below code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(string DOB)
        {
            if (string.IsNullOrEmpty(DOB.Trim()))
            {
                ModelState.AddModelError("DOB", "The Date Of Birth field is required.");
            }
            return View();
        }
    }
}

Adding View

Now, right click on home controller index action method, add new view and name Index. Select Empty template and uncheck Use layout page and click on Add as shown below.

Addling index view

Now go to Views / Home folder, open Index.cshtml file and replace all code with below code.
Here in script JS files, First is jQuery file and Second, Third is jquery-ui JS and CSS files which is compulsory. Make sure all files are loaded when application runs.

Index.cshtml Code:
@model WebApplication1.Models.Employee

<title>DatePicker or Calendar Control in ASP.NET MVC using jQuery</title>

@* compulsory : for jquery to work *@
<script src="~/Scripts/jquery-3.2.1.js"></script>
@* compulsory : for jquery datepicker to work *@
<script src="~/Scripts/jquery-ui-1.12.1.js"></script>
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />

@* optional : for data annonation to work at client machine *@
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
@* optional : for bootstrap *@
<script src="~/Scripts/bootstrap.js"></script>
<link href="~/Content/bootstrap.css" rel="stylesheet" />

<script>
    $(document).ready(function () {
        $("#DOB").datepicker();
    });
</script>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <table class="table table-striped table-dark">
        <tbody>
            <tr>
                <td>
                    <div class="form-group">
                        @Html.LabelFor(model => model.DOB, new { @class = "control-label col-md-2" })
                        @Html.TextBoxFor(model => model.DOB, new { @class = "form-control col-md-2", style = "width:200px;" })
                        @Html.ValidationMessageFor(model => model.DOB, "", new { @class = "text-danger col-md-3" })
                    </div>
                </td>
            </tr>
            <tr>
                <td>
                    <div class="form-group">
                        <div class="col-md-offset-2 col-md-4">
                            <input type="submit" value="Insert" class="btn btn-primary" style="width:100px;" />
                            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                        </div>
                    </div>
                </td>
            </tr>
        </tbody>
    </table>
}
When application runs then view can be seen as below.
Data annonation in ASP.NET MVC using unobtrusive js
Now click on insert button, you can see calendar is attached to DOB textbox and required field data annotation is also worked.
DatePicker control in ASP.NET MVC using jQuery UI

Now by-default only month is displaying, you can modify javascript to display month, year and date format as shown below.

<script>
    $(document).ready(function () {
        $("#DOB").datepicker({
            dateFormat: "dd-mm-yy",
            changeMonth: true,
            changeYear: true,
            //showButtonPanel: true
        });
    });
</script>
DatePicker with month and year in jQuery UI

You can also specify the animation, max date ,min date ,date range etc as shown below.

<script>
    $(document).ready(function () {
        $("#DOB").datepicker({
            dateFormat: "MM dd, yy", //"MM dd, yy"   "dd-mm-yy",    "DD, dd MM, yy"
            showAnim: "fold", //bounce , fold, slideDown
            minDate: "-30Y",
            maxDate: "-1"//  + -   M for month
            changeMonth: true,
            changeYear: true,
            // yearRange: "2005:2020"
        });
    });
</script>

You can also overwrite the css of datepicker as shown below.

DatePicker with custom css in jQuery UI
CSS Code
<style>
    .ui-datepicker {
        width: 17em;
        padding: .2em .2em 0;
        display: none;
        background: #2F99B4;
    }

    .ui-datepicker .ui-datepicker-title {
        margin: 0 2.3em;
        line-height: 1.8em;
        text-align: center;
        color: #FFFFFF;
        background: #2F99B4;
    }

    .ui-datepicker .ui-datepicker-title select {
        color: #000;
    }

     .ui-datepicker table {
         width: 100%;
         font-size: .7em;
         border-collapse: collapse;
         font-family: verdana;
         margin: 0 0 .4em;
         color: #000000;
         background: #9EEFEE;
     }
     /*This is date TD */
     .ui-datepicker td {
         border: 0;
         padding: 1px;
     }

    .ui-datepicker td span,
    .ui-datepicker td a {
        display: block;
        padding: .8em;
        text-align: right;
        text-decoration: underline;
    }
</style>
Share:

0 comments:

Post a Comment

Email Subscription

Subscribe to our newsletter to get the latest articles directly into your inbox

Blog Archive

Ads By Chitika