Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use the jQuery UI Datepicker with MVC's Html.TextBoxFor?

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?

like image 223
Matt Avatar asked May 27 '10 20:05

Matt


2 Answers

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.

like image 181
Jab Avatar answered Oct 06 '22 07:10

Jab


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.

like image 30
Kevin LaBranche Avatar answered Oct 06 '22 07:10

Kevin LaBranche