2

When scaffolding a view from a model with the property below it produces code that renders a browser date picker which works great.

How can you scaffold a property that produces a date and TIME picker?

[Display(Name = "Date Start")]
[DataType(DataType.Date)]
public DateTime EventStart { get; set; }

I tried this but it doesn't work ...

[DataType(DataType.DateTime)]
teo van kot
  • 12,350
  • 10
  • 38
  • 70
Art Vdel
  • 87
  • 6
  • I bet you can't do it with default scaffolds. Check [this answer](http://stackoverflow.com/a/38054088/1849444) for more details – teo van kot Jan 09 '17 at 10:48
  • 1
    _that renders a browser date picker which works great_ - only if your using Chrome or Edge - its not supported in IE or FireFox and your users will just see a textbox. –  Jan 09 '17 at 11:00

1 Answers1

1

You can achieve this by creating a custom EditorTemplate and tell MVC to use it with [UIHint].

ViewModel:

[Display(Name = "Date Start")]
[UIHint("DateTimePicker")]
public DateTime EventStart { get; set; }

Views/Shared/EditorTemplates/DateTimePicker.cshtml:

@model DateTime

<input type="text" name="@Html.NameFor(m => m)" id="@Html.IdFor(m => m)" value="@Model.ToString("o")"/>
<script type="text/javascript">
    // init the datepicker of your JS UI Framework (I am using jQuery UI here)
    $('#@Html.IdFor(m => m)').datepicker(); 
</script>

Usage in Main View:

@Html.EditorFor(m => m.EventStart)

The problem with this approach is that you loose the handle on the JS datepicker object created in the EditorTemplate. So if you want to change the configuration (e.g. set the maxDate dynamically), you have to build additional infrastructure.

So my recommendation is to attach the JS datepicker directly in the view that needs it and configure it there instead of using Editor Templates for datepickers.

Georg Patscheider
  • 9,357
  • 1
  • 26
  • 36