Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's a technique i use to split a date into 3 fields, while only having 1 DateTime property on the ViewModel. While not exactly what you're after, you should be able to use a similar method to achieve what you want.</p> <p><strong>Editor Template</strong> <em>/views/shares/editortempaltes/datetime.cshtml</em></p> <pre><code>@model Nullable&lt;System.DateTime&gt; @Html.TextBox("Day", Model.HasValue ? Model.Value.Day.ToString() : "", new { Type = "Number", @class="date-day" }) @Html.ValidationMessage("Day") @Html.DropDownList("Month", months, new { @class="date-month" }) @Html.ValidationMessage("Month") @Html.TextBox("Year", Model.HasValue ? Model.Value.Year.ToString() : "", new { Type = "Number", @class="date-year" }) @Html.ValidationMessage("Year") </code></pre> <p><strong>Custom ModelBinder</strong></p> <pre><code>public object GetValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) { int day, month, year; if (TryGetValue(controllerContext, bindingContext, propertyDescriptor.Name + ".Day", out day) &amp;&amp; TryGetValue(controllerContext, bindingContext, propertyDescriptor.Name + ".Month", out month) &amp;&amp; TryGetValue(controllerContext, bindingContext, propertyDescriptor.Name + ".Year", out year)) { try { return new DateTime(year, month, day); } catch (ArgumentOutOfRangeException) { var fullPropertyName = bindingContext.ModelName + "." + propertyDescriptor.Name; bindingContext.ModelState[fullPropertyName] = new ModelState(); bindingContext.ModelState[fullPropertyName].Errors.Add("Invalid date"); } } return null; } private bool TryGetValue(ControllerContext controllerContext, ModelBindingContext bindingContext, string propertyName, out int value) { var fullPropertyName = bindingContext.ModelName + "." + propertyName; string stringValue = controllerContext.HttpContext.Request[fullPropertyName]; bindingContext.ModelState.Add(fullPropertyName, new ModelState() { Value = new ValueProviderResult(stringValue, stringValue, null) }); return int.TryParse(stringValue, out value); } </code></pre> <p><strong>Usage</strong> Add a DateTime property to your ViewModel, then call</p> <pre><code>@Html.EditorFor(m =&gt; m.DateTimeProperty) </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload