Tuesday 15 February 2011

How to display a jQuery datepicker control in an ASP.NET MVC partial view

When trying to use the jQuery datepicker in an ASP.NET MVC partial view I found that the calendar didn't display correctly.  On investigating the problen I realized I was calling the datepicker function in the wrong place.  Calling it in the partial view doesn't work - the MVC framework ignores the script when it renders the partial view in the .aspx view.  Calling it in the .aspx view's document ready event doesn't work either because at this stage it doesn't know about the control.

Here's a way to get it working.

Firstly, link the jQuery UI CSS file in the head section of the master file:

<link type="text/css" href="../../Content/jquery-ui-1.8.9.custom.css" rel="stylesheet" />

Add the jQuery script references to the head section of the master file (or in the appropriate asp:Content section in the .aspx view in which you're posting the partial view):

<script type="text/javascript" src="../../Scripts/jquery-1.4.1.js"></script>
<script type="text/javascript" src="../../Scripts/jquery-ui-1.8.9.custom.min.js"></script>

Create a Javascript function that calls the datepicker function:

<script type="text/javascript">
    function showDatePicker() {
        $('#date').datepicker();
    }
</script>

Declare the input element in the partial view, making sure to give it the same id you used in the call to datepicker:

<input type="text" name="date" id="date" />

Finally (this is the crucial bit), you need to call this function in the OnSuccess parameter of the Ajax call in the .aspx view, e.g.:

<li><%= Ajax.ActionLink("Some text to click on", "action_name", new { Id = Model.Id }, new AjaxOptions { OnSuccess = "showDatePicker", UpdateTargetId = "div_name" })%></li>

Note that this doesn't work if you use the OnComplete parameter.