Apr 15, 2011 at 7:45 PM
Edited Apr 15, 2011 at 8:40 PM
In order to handle properly DateTime? and in generale any type that can assume a null value you need to use the technique exposed in
Handling optional input and mutually exclusive inputs. There re is no way for the user to "put" a null value into a DateTimeInput,
that's why you can' figure out how to do it.... If you use a simple textbox you can use the convention that an empty string represents a null value, however other input types don't give this opportunity. That's why, in the Mvc Controls Toolkit I defined
ad hoc tools to handle optional values. The right way to proceed is to add someway a checkbox(or...something else) to enable the user to specify he don't want to provide a date, so you have to "transform" DateTime? into DateTime+Boolean by usingn
an in-line transformation:
var hi = Html.TransformedUpdateHelper(m => m.Start, new NullableUpdater<DateTime>());//transformed helper
var DTS = hi.DateTimeFor(m => m.Item, DateTime.Now); //now you have transformed the DateTime? into DateTime +Boolean
<%:hi.CheckBoxFor(m => m.Chosen) %><%: DTS.Date() %> <%: DTS.Time() %>
For more info about in-line transformations please see : In-Line Transformations.
For more info about how to handle nullable types and, optional and mutually exclusive input see: Handling optional input and mutually
Another way to proceed is by passing directly the DateTime? to the DateInput but make the date appears/disappears when pressing a checkbox. The
ViewsOnOff, can make input fields appear disappear, by detaching/attaching them from the DOM. In this case you can write:
<%:Html.ViewsOnOff("startDate", Model.Start.HasValue) %>
//initially the Date is shown if and only if the DateTime? has a value
<%var DTS = Html.DateTime("Start", Model.Start); %>
<input type='checkbox' class="startDate_checkbox"/>
<%: DTS.Date() %> <%: DTS.Time() %>
For a better understanding, please see the documentation of the ViewsOnOff.
This is the technique I prefer with simple types like the DateTime?, since the in-line transformation of a simple type "detach it" from its original father(a new father is put in between the old father and the child), and consequentely client side validation
is not applied(validation attributes are applied on the original father). On the server the temporay father is cancelled so validation is performed normally. For complex types like a whole customer entity the insertion of a "temporary" father doesn't create
Please, doesn't esitate to contact me for more explanations if the documentation is not enough clear, so I can improve the documentation.