Thursday, January 19, 2012

Add jQuery DatePicker to MVC 3


Add jQuery DatePicker to MVC 3  - 18 Jan 12

Add the DataType attribute to the date field in your model



Note:  This will also remove the time from the display.

Create the partial view Views\Shared\EditorTemplates\Date.cshtml

@model DateTime?
@Html.TextBox("", Model.HasValue ? Model.Value.ToShortDateString() : DateTime.Today.ToShortDateString(), new { @class = "date" })
<script type='text/javascript'>
    $(document).ready(function () {
        $('.date').datepicker({ dateFormat: "mm/dd/yy" });
    });
</script>

Note:  You can put this JavaScript in a separate script file and reference that in _Layout.cshtml if you would rather not have it here.

Add the necessary links to Views\Shared\_Layout.cshtml

<link href="../../Content/themes/base/jquery.ui.all.css" rel="stylesheet" type="text/css" />
<script src="../../Scripts/jquery-ui-1.8.11.min.js" type="text/javascript"></script>


References






No comments:

Post a Comment