implement DateTimePicker in MVC

Updated : Oct 28, 2019 in Articles

How to implement DateTimePicker in MVC

In this article, we will discuss how to implement DateTimePicker in MVC a simple way using jquery

implement DateTimePicker in MVC
implement DateTimePicker in MVC

Steps for implement DateTimePicker in MVC

  1. creating a model class
  2. Implementing the action method in the controller
  3. implementing the view
  4. use external CDN’s or install the Jquery UI form Manage Nuget Package
  5. Implementing jquery for DateTimePicker

Step 1: Create a model Class

Go to visual studio create a new Asp.net MVC project, create a model class inside model folder name like StudentModel And Add given below snippet code

 public class StudentModel
    {
        public int StudentId { get; set; }
        [Display(Name = "From Date")]
        [DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}", ApplyFormatInEditMode = true)]
        public DateTime FromDate { get; set; }
        [DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}", ApplyFormatInEditMode = true)]
        [Display(Name = "To Date")]
        public DateTime ToDate { get; set; }
    }

Step 2: Implementing the action method in the controller

Assign the FromDate and ToDate values to student model object

FromDate = DateTime.Now,
ToDate = DateTime.Now.AddDays(1)

follow the given below snippet code

 public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            StudentModel objStudentModel = new StudentModel()
            {
                FromDate = DateTime.Now,
                ToDate = DateTime.Now.AddDays(1)
            };
            return View(objStudentModel);
        }

        [HttpPost]
        public ActionResult Index(StudentModel objStudentModel)
        {
            return Content(((objStudentModel.ToDate - objStudentModel.FromDate).TotalDays).ToString());
        }
    }

Step 3: implementing the view

you will implement view for Index action method with the help of following given bellow snippet code

<div class="container">
    <div class="row">
        <div class="form-group">
            @Html.LabelFor(model => model.FromDate, new {@class = "control-label"})
            @Html.EditorFor(model => model.FromDate, new { htmlAttributes = new { @readonly = "true" , Value = Model.FromDate.ToString("dd-MMM-yyyy"), @class = "form-control datepicker", @id= "txtFromDate" } })
        </div>
    </div>
    <div class="row">
        <div class="form-group">
            @Html.LabelFor(model => model.ToDate, new { @class = "control-label" })
            @Html.EditorFor(model => model.ToDate, new { htmlAttributes = new { @readonly = "true" , Value = Model.ToDate.ToString("dd-MMM-yyyy"), @class = "form-control datepicker", @id = "txtToDate" } })
        </div>
    </div>
    <div class="row">
        <div class="form-group">
            <input id="btnSave" type="button" name="Show" value="Show" class="btn btn-danger"/>
        </div>
    </div>
</div>

Step 4: use external CDN’s or install the Jquery UI

Given below CDN’s are required for Implementing DateTimePicker in MVC or go to manage NuGet package console install the jquery UI

Add given below CDN’s are layout page level or index page level or If you have in these files in your Script folder go to the App_Start folder and open BundleConfig.cs Add js file to bundle.

bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(  
          "~/Scripts/jquery-ui-{version}.js"));  

bundles.Add(new StyleBundle("~/Content/cssjqryUi").Include(  
       "~/Content/jquery-ui.css")); 

OR

<script src="~/scripts/jquery-1.12.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet" />

Step 5: Implementing jquery for DateTimePicker

Add given below Snippet code in your Index View page

<script type="text/javascript">
    $(document).ready(function() {
        DateTimePicker();
        $("#txtFromDate").change(function() {
            var date2 = $("#txtFromDate").datepicker('getDate', '+1d');
            console.log(date2);
            date2.setDate(date2.getDate() + 1);
            $("#txtToDate").datepicker('option', 'minDate', date2);
            $("#txtToDate").datepicker('setDate', date2);
        });

        $("#btnSave").click(function() {
            alert($("#txtFromDate").val());
            alert($("#txtToDate").val());
            var objStudentModel = { FromDate: $("#txtFromDate").val(), ToDate: $("#txtToDate").val() };
            $.ajax({
                async: true,
                type: 'POST',
                dataType: 'JSON',
                contentType: 'application/json; charset=utf-8',
                data: JSON.stringify(objStudentModel),
                success: function() {
                    alert('da');
                },
                error: function() {

                }
            });
        });
    });

    function DateTimePicker() {
        $(".datepicker").datepicker({
            dateFormat: 'dd-M-yy',
            changeMonth: true,
            changeYear: true,
            showOn: 'button',
            sideBySide : true,
            controlType: 'select',         
            buttonText: '<span class="glyphicon glyphicon-calendar" ></span>',
            minDate: new Date()
        });
    }

</script>

Run your Application thanks.

Latest posts by DuttaluruVijayakumar (see all)
Like
Like Love Haha Wow Sad Angry

Subscribe
Notify of
guest
6 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Vernon Finizio
April 9, 2020 3:16 pm

tҺe website іѕ really good, I really like it!

Perry Quilliams
April 10, 2020 11:28 am

tҺe website іѕ really good, I like your web site!

Thanh Shuttleworth
Thanh Shuttleworth
April 16, 2020 10:37 pm

First time visiting your website, I really like it!

Salvatore Tokihiro
Salvatore Tokihiro
April 21, 2020 11:12 pm

Saved as a favorite!, I really like it!

Arthur Iadarola
April 25, 2020 10:49 pm

tҺe website іѕ really good, I love your web site!

Junior Yang
April 28, 2020 6:04 am

tҺe website іѕ really good, I like it!

6
0
Would love your thoughts, please comment.x
()
x