我在ASP .NET MVC 5.1中编写应用程序
我有一个字段:
[DisplayName("Date of Birth")]
[DataType(DataType.Date)]
public DateTime BirthDate { get; set; }
然后在视图中
<div class="form-group">
@Html.LabelFor(model => model.BirthDate, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.BirthDate, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.BirthDate, "", new { @class = "text-danger" })
</div>
</div>
转换为:
如果我只是将模型中属性的注释更改为:
[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特定的解决方案。
答案 0 :(得分:5)
由于html5和浏览器支持html5,你得到这个日期选择器。 可能的选择:
答案 1 :(得分:5)
您的要求非常挑剔 ......
为字段指定属性Datatype
,将生成input
,其中指定的属性为type
。这就是为什么当您添加[DataType(DataType.Date)]
时,生成的输入将是日期选择器,但如果您添加[DataType(DataType.DateTime)]
,则输入将为datetime
类型,因此您无法获得任何输入选择器显示。为什么?因为几年前,支持输入datetime
的浏览器决定停止支持它,W3C由于缺乏实现而删除了此功能。
但是,不久前,一些浏览器供应商再次开始支持datetime-local
,这又回到了草案上。截至目前,最新版本的Chrome
,Opera
和Microsoft Edge
都支持它。
一种解决方案是使用Ajay Kumar建议的BootStrap或jQuery Datetime Picker。
如果你不介意几个支持的浏览器,那么另一个就是使用datetime-local
。比如这样:
@Html.TextBoxFor(model => model.BirthDate, new { type = "datetime-local"})
答案 2 :(得分:1)
我的解决方案略有不同。虽然它确实使用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日期时间选择器。 您可能想要更改日期时间选择器的默认值。希望这可以帮助别人。
答案 3 :(得分:0)
添加对象定义:
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中添加为:
<div class="form-group">
@Html.LabelFor(m => m.RegistedDate, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@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" })
</div>
</div>