在ASP .NET MVC 5.1 / HTML 5中显示DateTime选择器而不是日期选择器
我在ASP .NET MVC 5.1中编写应用程序
我有一个领域:
[DisplayName("Date of Birth")] [DataType(DataType.Date)] public DateTime BirthDate { get; set; }
然后在视图中
@Html.LabelFor(model => model.BirthDate, htmlAttributes: new { @class = "control-label col-md-2" }) @Html.EditorFor(model => model.BirthDate, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.BirthDate, "", new { @class = "text-danger" })
转换为:
如果我只是将模型中的属性上面的注释更改为:
[DisplayName("Date of Birth")] [DataType(DataType.DateTime)]
我没有显示任何选择器。 如果我将它们更改为:
[DisplayName("Date of Birth")] [DataType(DataType.Time)]
只有hh:mm可供选择。
问题:在ASP .NET MVC 5.1中显示DateTime选择器而不是日期选择器。 我要求ASP .NET 5.1 HTML 5特定的解决方案。
由于html5和支持html5的浏览器,你得到这个日期选择器。 可能的选择:
- BootStrap日期时间选择器
- jQuery日期时间选择器
你的要求很挑剔 ……
为字段指定属性Datatype
将生成具有指定属性Datatype
的input
。 这就是为什么当你添加[DataType(DataType.Date)]
,生成的输入将是一个日期选择器,但如果添加[DataType(DataType.DateTime)]
,输入将是datetime
类型,因此你不这样做显示任何选择器。 为什么? 因为几年前,支持输入datetime
时间的浏览器决定停止支持它,而W3C由于缺乏实现而删除了这个function。
然而,不久前,一些浏览器供应商开始再次支持datetime-local
,这又回到了草案上。 截至目前,最新版本的Chrome
, Opera
和Microsoft Edge
支持它。
一种解决方案是使用BootStrap或jQuery Datetime Picker,就像Ajay Kumar建议的那样。
如果你不介意几个支持的浏览器,另一个是使用datetime-local
。 比如这样:
@Html.TextBoxFor(model => model.BirthDate, new { type = "datetime-local"})
我的解决方案略有不同。 虽然它确实使用javascript / jQuery来完成。 如果您使用数据注释,我会使用Fact
[Display(Name = "The Display Name")DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yy H:mm:ss tt}"), DataType(DataType.DateTime)] public DateTime DateTimeFieldName { get; set; }
现在你必须在页面上(或在一个包中)包含jqueryUI脚本和CSS。 在Javascript中:
$(function () {//DOM ready code // Get data-annotations that are Marked DataType.DateTime and make them jquery date time pickers $('input[type=datetime]').datetimepicker({ dateFormat: 'yy-mm-dd', timeFormat: 'hh:mm', changeMonth: true, changeYear: true, showAnim: 'slideDown' }); });// END DOM Ready
由于DataType(DataType.DateTime)
使用类型为datetime的输入。 只需使用这个事实并采用所有这些并使用jQuery使它们成为日期时间选择器。 我有这个代码包含在我的_Layout
页面包中。
所以现在我所要做的就是在模型中注释属性,它将显示为jQuery日期时间选择器。 您可能想要更改日期时间选择器的默认值。 希望这有助于某人。
添加对象定义:
public class EditViewModel { public string Id { get; set; } [Display(Name = "Username")] public string UserName { get; set; } [DataType(DataType.Date)] [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-ddThh:mm:ss}")] [Display(Name = "Registed Date")] public DateTime RegistedDate { get; set; } }
在.cshtml中添加为:
@Html.LabelFor(m => m.RegistedDate, new { @class = "col-md-2 control-label" }) @Html.TextBoxFor(m => m.RegistedDate, "{0:yyyy-MM-ddThh:mm:ss}", new { @class = "form-control", type = "datetime-local" }) @Html.ValidationMessageFor(m => m.RegistedDate, "", new { @class = "text-danger" })