Question

I am using the jQuery DatePicker control in an ASP.NET MVC application.

I created a control called DateTime.ascx, so that whenever I call the Html.TextBoxFor() method passing it a field of type DateTime, this control comes into play, and a textbox+datepicker is rendered, overriding the standard functionality which produces just a textbox.

This is the control:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime?>" %>
<%=Html.TextBox("", 
    (Model.HasValue ? Model.Value.ToString("MM/dd/yyyy") : DateTime.Today.ToShortDateString()), 
    new { @class = "UseDatePicker" } )%>

And here is an example call:

<%: Html.EditorFor(model => model.Project.IssueDate)%>

Now, I also include on the master page a script called DatePickerConfig.js which, well, configures the datepicker. Here it is:

$(document).ready(function () {
    $(".UseDatePicker").live('click', function () {
        $(this).datepicker('destroy').datepicker({
            showOn: "both",
            buttonImage: "../../Content/calendar.gif",
        buttonImageOnly: true,
            changeMonth: true,
            changeYear: true
        }).focus();
    });
});

Now, my problem: when the page loads, only a text box appears for editing the datetime field. When I click on the textbox, the calendar pops out as expected, and at the same time the button image appears. What I would like is for the buttonn image to be visible as soon as the page loads, and before the user starts to interact with the control.

Thanks.

Was it helpful?

Solution

The problem is you aren't binding the datepicker until you click on the textbox, so there is no button to bind until that loads. You should just bind the datepicker, Is there a reason you unbind and rebind on every button click? Per your current explanation, this would make more sense:

$(document).ready(function () {
    $(".UseDatePicker").each(function(i) {
        $(this).datepicker({
            showOn: "both",
            buttonImage: "../../Content/calendar.gif",
            buttonImageOnly: true,
            changeMonth: true,
            changeYear: true
        });
    });
});

This will go through each field expecting a datepicker and bind the picker to that textbox.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top