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)]
1 个解决方案
#1
1
You can achieve this by creating a custom EditorTemplate and tell MVC to use it with [UIHint]
.
您可以通过创建自定义编辑器模板并告诉MVC使用[UIHint]来实现这一点。
ViewModel:
视图模型:
[Display(Name = "Date Start")]
[UIHint("DateTimePicker")]
public DateTime EventStart { get; set; }
Views/Shared/EditorTemplates/DateTimePicker.cshtml:
视图/共享/ 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.
这种方法的问题是,您丢失了在EditorTemplate中创建的JS datepicker对象的句柄。因此,如果您想要更改配置(例如动态设置maxDate),则必须构建额外的基础设施。
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.
因此,我的建议是直接将JS datepicker附加到需要它的视图中,并在那里配置它,而不是使用datepickers的编辑器模板。
#1
1
You can achieve this by creating a custom EditorTemplate and tell MVC to use it with [UIHint]
.
您可以通过创建自定义编辑器模板并告诉MVC使用[UIHint]来实现这一点。
ViewModel:
视图模型:
[Display(Name = "Date Start")]
[UIHint("DateTimePicker")]
public DateTime EventStart { get; set; }
Views/Shared/EditorTemplates/DateTimePicker.cshtml:
视图/共享/ 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.
这种方法的问题是,您丢失了在EditorTemplate中创建的JS datepicker对象的句柄。因此,如果您想要更改配置(例如动态设置maxDate),则必须构建额外的基础设施。
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.
因此,我的建议是直接将JS datepicker附加到需要它的视图中,并在那里配置它,而不是使用datepickers的编辑器模板。