jQuery DatePicker with month and year menus in MVC3 Razor



  1. In this article we will see how to display month and year dropdown menus in jQuery DatePicker.
  2. Using this menus, we can select any month and year from dropdown instead of moving to required month or year by clicking next or previous images.
  3. We will use this jQuery DatePicker with MVC3 Razor application.
  4. We can show month and year dropdown on datepicker by setting boolean parameters changeMonth and changeYear to true.

Following are the steps :

ViewModel :

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

namespace jQueryDatePicker.Models
{
    public class Register
    {
        public DateTime DOB { get; set; }
    }
}

View :


@model jQueryDatePicker.Models.Register
@{
    Layout = "../Shared/_Layout.cshtml";
}

<!DOCTYPE html>

@Html.EditorFor(Model => Model.DOB)

<script type="text/javascript">

    $(document).ready(function () {
        $("#DOB").datepicker({
            changeMonth: true,
            changeYear: true
        });
    });
</script>

We have used EditorFor helper to render control for our ViewModel property. In the script section we have set the boolean properties changeMonth and changeYear to true.

Layout :



<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.8.3.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.ui.datepicker.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.ui.widget.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.ui.core.min.js")" type="text/javascript"></script>
    <link href="@Url.Content("~/Content/themes/base/jquery.ui.all.css")" rel="stylesheet" type="text/css" />
</head>

<body>
    @RenderBody()
</body>
</html>

Demo :

Click inside textbox to open datepicker.


Thus by setting the changeYear and changeMonth parameters, we can display the dropdowns to select year and month respectively.

0 comments:

Post a Comment