jQuery DatePicker and customization in MVC3 Razor



  1. In this article we will see how to use DatePicker in MVC3 Razor. 
  2. We do not have html helper to render DatePicker in MVC3.
  3. We are going to use jQuery DatePicker to fulfill our requirement.

Following are the steps to render simple DatePicker :

ViewModel :

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

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

We have created a ViewModel. We have defined a property named DOB of type DateTime. We are going to bind our view with this ViewModel.

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();
    });
</script>

Our View looks as above. We have include the reference of our ViewModel. We have used EditorFor helper to render control for address property. We have also added the script section. In the script section we have used id of control to select the control and used datepicker() method to render datepicker.

Demo :


Click inside TextBox


We have include following jQuery reference in the layout file to datepicker to work.

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>

Include above references in your layout and refer this layout in your view.


Following above steps we can use jQuery DatePicker for our MVC3 application.



More on jQuery DatePicker :



0 comments:

Post a Comment