c# - 在特定于 ASP .NET MVC 5.1/HTML 5 中显示日期时间选择器而不是日期选择器

标签 c# razor datepicker asp.net-mvc-5.1

我在 ASP .NET MVC 5.1 中编写应用程序

我有一个字段:

  [DisplayName("Date of Birth")]
  [DataType(DataType.Date)]
  public DateTime BirthDate { get; set; }

然后在 View 中

  <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>

转化为:

enter image description here

如果我只是将模型中属性上方的注释更改为:

    [DisplayName("Date of Birth")]
    [DataType(DataType.DateTime)]

我没有显示任何选择器。如果我将它们更改为:

 [DisplayName("Date of Birth")]
 [DataType(DataType.Time)]

只有hh:mm可供选择。

问题:在 ASP .NET MVC 5.1 中显示日期时间选择器而不是日期选择器。我要求 ASP .NET 5.1 HTML 5 特定解决方案。

最佳答案

你的要求很挑剔...

为字段指定属性 Datatype,将生成一个 input,其具有指定的属性 type。这就是为什么当您添加 [DataType(DataType.Date)] 时,生成的输入将是一个日期选择器,但是如果您添加 [DataType(DataType.DateTime)],输入将是 datetime 类型,因此您没有显示任何选择器。为什么?因为几年前,支持输入 datetime 的浏览器决定停止支持它,W3C 由于缺乏实现而删除了这个特性。

然而,不久前,一些浏览器供应商又开始支持 datetime-local,它又回到了草案中。截至目前,最新版本的 ChromeOperaMicrosoft Edge 都支持它。

一种解决方案是按照 Ajay Kumar 的建议使用 BootStrap 或 jQuery Datetime Picker。

如果您不介意少数支持的浏览器,另一种方法是使用 datetime-local。例如这样:

@Html.TextBoxFor(model => model.BirthDate, new { type = "datetime-local"})

关于c# - 在特定于 ASP .NET MVC 5.1/HTML 5 中显示日期时间选择器而不是日期选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25765750/

相关文章:

c# - 将 Razor 页面呈现为字符串

html - Razor、StringBuilder、HTML 换行符?

javascript - 如何在 Datepicker 中将 beforeShowDay 与 foreach 一起使用

iphone - 修改iphone SDK中的日期选择器

c# - 如何在第一次运行时自动创建数据库?

javascript - CSS/Less 中的 Razor ?

c# - 如何轻松地将原始文本 block 表示为字符串?

iphone - 时间模式下的 UIDatePicker - 如何获得唯一的 "hour value"

c# - 将非终止流中的对象集合转换为 IObservable

c# - 通过组合两列来选择不同的项目,其中第三列的值为 max-LINQ