On my MVC3 razor page I have a date field
@Html.EditorFor(model => model.Member.Dob)
Given below is the code I am trying to get a datepicker for the Date of Birth field.
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
debugger;
$("#Member_Dob").datepicker();
});
</script>
But when I run this page I am getting error
Microsoft JScript runtime error: Object doesn't support property or method 'datepicker'
Please help me find a way to add datepicker to my page
The Html. Editor() or Html. EditorFor() extension methods generate HTML elements based on the data type of the model object's property. The following table list the data types and releted HTML elements: DataType.
For most datepickers, simply set data-provide="datepicker" on the element you want to initialize, and it will be intialized lazily, in true bootstrap fashion. For inline datepickers, use data-provide="datepicker-inline" ; these will be immediately initialized on page load, and cannot be lazily loaded.
On the All tab of the Property Sheet, make sure the Show Date Picker property is set to For dates. On the Data tab of the property sheet, type =Date() in the Default Value property for the field. Note: If you want to include the current time as well as the date, use the Now() function instead of Date().
You'll need to create an EditorTemplate in your Views\Shared\EditorTemplate folder. Name it DateTime.cshtml. Should look something like the following:
@model System.DateTime?
<div class="editor-label">
@Html.Label("")
</div>
<div class="editor-field">
@Html.TextBox("", String.Format("{0:MM/dd/yyyy}",(Model == DateTime.MinValue)? null : Model), new { @class="text"})
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#@ViewData.ModelMetadata.PropertyName").datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'mm/dd/yy',
gotoCurrent: true
});
});
</script>
Use it as follows:
@Html.EditorFor(model => model.Member.Dob)
This article covers this perfectly: http://blogs.msdn.com/b/stuartleeks/archive/2011/01/25/asp-net-mvc-3-integrating-with-the-jquery-ui-date-picker-and-adding-a-jquery-validate-date-range-validator.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With