How to integrate JQuery UI Datepicker in MVC

May 05, 2014 by Anuraj

.Net .Net 4.0 ASP.Net ASP.Net MVC HTML5 Javascript

This post is about integrating JQuery UI DatePicker in MVC 4. First you need to modify the _layout.cshtml. Because by defualt, it won’t include required references for JQuery UI. You need to include both CSS and JS for JQuery UI references. So the modified _layout.cshtml will look like this.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Styles.Render("~/Content/themes/base/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    @RenderBody()

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/bundles/jqueryui")
    @RenderSection("scripts", required: false)
</body>
</html>

And in the CSHTML where you want to include the JQuery Date Picker, include the following snippet.

$(function () {
    $("#JoiningDate").datepicker();
});

Clicking on the textbox will popup calender like this.

JQuery UI DateTime Picker in MVC

It works perfectly, until validations come in to the play :) As my application is targeted to India / UK customers, I have added a formatting to DatePicker like this.

$(function () {
    $("#JoiningDate").datepicker({
        dateFormat: 'dd/mm/yy'
    });
});

But MVC validator controls didn’t recognize the textbox value as a valid date time.

JQuery UI DateTime Picker in MVC - Date Validation fails

To resolve this issue, you need to override the date validation behaviour of JQuery validation library. You can do this by adding following snippet.

$(function () {
    $.validator.addMethod("date", function (value, element) {
        var ok = true;
        try {
            $.datepicker.parseDate('dd/mm/yy', value);
        }
        catch (err) {
            ok = false;
        }
        return ok;
    });
});

Also you need to add the Display Format attribute to the Model property.

[Required]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}",
    ApplyFormatInEditMode = true)]
public DateTime JoiningDate { get; set; }

Happy Programming :)

Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub