Brad Wilson has recently completed a blog series about Templates in MVC 2. I really like this feature as it provides me with the ability to quickly generate screens, even if eventually I might have to go back and rework them. Basically I want to have my cake and eat it – I want the initial productivity of a scaffolding based approach but the flexibility to customize look and feel when required.
By default an text box is generated for DateTime fields. What I wanted to do was hook this up to the excellent Datepicker widget from jQuery UI. Here’s how I achieved this:
- Add the following 3 references to the Master Page:
<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js”></script>
<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js”></script>
<link href=”http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/overcast/jquery-ui.css” type=”text/css” rel=”Stylesheet” class=”ui-theme” />I am referencing jQUery and jQUery UI from the Google CDN (great for getting started quickly as well as for production scenarios). I am also linking to one of the default themes which goes nicely with the default MVC stylesheet.
- Add the following Javascript to the Master Page:<script type=”text/javascript”>
$(function () {
$(“.date-edit-box”).datepicker();
});
</script>Here I am simply looking for a specific class and attaching a Datepicker widget to it. I am aware that this is not the most efficient approach as the code might run unnecessarily but it’s perfect for a demo.
- Ensure that the correct class is rendered by the Template. Apparently you can currently only override the default templates for individual Controllers. Therefore create a Views/{ControllerName}/EditorTemplates folder and within it create a file called DateTime.ascx which should contain:
- You’ll probably want to use the DIsplayFormatAttribute on the DateTime fields in the View Model to ensure that the time is not also output (don’t forget to set the ApplyFormatInEditMode property to true if you do this).
<%@ Control Language=”C#” Inherits=”System.Web.Mvc.ViewUserControl” %>
<%= Html.TextBox(“”, ViewData.TemplateInfo.FormattedModelValue, new { @class = “date-edit-box” }) %>
That’s it. You should now see Datepickers for the appropriate fields that were rendered using the Html.EditorForModel() extension method.
Hi, you can actually use a folder called “Views/Shared/EditorTemplates”
which prevents you from having to duplicate the view.
Julian.
Thanks Julian…I knew there had to be a way.