I am using Model binding with the Entity Framework and have an Html.TextBoxFor(model =>model.date) input. I know how to tell jQuery how to implement a datepicker but not in this context. What would I need to add here to have a calendar popup when the user enters this field?
You'll want to use the HtmlHelper overload that allows you to specify Html attributes. Then target them with the jquery selector.
// in view
<%= Html.TextBoxFor(x => x.Date, new { @class="datepicker" })%>
// in js
$(document).ready({
$('.datepicker').datepicker();
});
Though I recommend using EditorFor
instead.
<%= Html.EditorFor(x => x.Date)%>
You can create an EditorTemplate to handle any field that is a DateTime
and have it output the proper field.
Create /Views/Shared/EditorTemplates/DateTime.ascx
and put this in it...
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime>" %>
<%= Html.TextBox("", Model.ToShortDateString(), new { @class="datepicker" } )%>
Or if you need to allow DateTime's with nulls:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime?>" %>
<%= Html.TextBox("", (Model.HasValue? Model.Value.ToShortDateString():""), new { @class="datepicker"} )%>
Then you can always use EditorFor and have a central ascx to edit if you ever want to modify the way date times are handled in your views.
From the looks of your code sample (TextBoxFor) you are using MVC2....
Here's an example using MVC 2 that creates a template that will call the jQery date picker whenever you use a date & a second more in depth example.
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