【问题标题】:Using Data annotation in Model for DateTime在 Model for DateTime 中使用数据注释
【发布时间】:2017-04-13 10:56:38
【问题描述】:

我正在使用以下代码在我的剃刀视图中弹出 日期 的日历

型号

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
        [DataType(DataType.Date)]
        public Nullable<System.DateTime> EndTime { get; set; }

查看

<div class="form-group">
            @Html.LabelFor(model => model.EndTime, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-4">
                @Html.EditorFor(model => model.EndTime, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.EndTime, "", new { @class = "text-danger" })
            </div>
        </div>

现在我想使用 DateTime 而不是 Date。DataFormat 字符串应该是什么?

我的尝试

Display(Name = "End Date Time")]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}{1:HH/mm}")]
        [DataType(DataType.DateTime)]

我收到格式异常?

【问题讨论】:

  • 您是否尝试过简单的 DataFormatString = "{0:dd/MM/yyyy HH:mm}")]
  • 是的,我确实使用过,但在这种情况下,日历根本不会弹出。
  • 你用什么来显示日历?那是引导程序吗?
  • 我写了查看代码也请看。
  • 如果你想要 HTML-5 日期时间选择器,那么你需要使用@Html.TextBoxFor(m =&gt; m.EndTime, "{0:s}", new { @type = "datetime-local", @class = "form-control" })。但请注意,它仅在最新版本的 Chrome 和 Edge 中受支持

标签: c# asp.net-mvc format-string


【解决方案1】:

由于[DataType(DataType.Date)] 属性,您的EditorFor() 方法使用type="date" 呈现输入,这将生成浏览器HTML-5 日期选择器(但这仅在Chrome 和Edge 中受支持)。

要生成 HTML-5 日期时间选择器,您需要使用 type = "datetime-local" 呈现输入,但没有数据注释属性。相反,您需要自己生成type 属性。

@Html.TextBoxFor(m => m.EndTime, "{0:s}", new { @type = "datetime-local", @class = "form-control" })

注意"{0:s}""{0:yyyy-MM-ddTHH:mm:ss}" 的快捷方式,将在浏览器文化中显示日期和时间。另请注意,您不需要[DataType] 属性或[DisplayFormat] 属性中的ApplyFormatInEditMode = true 属性,因为它们仅适用于EditorFor()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-12
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 2016-11-14
    • 1970-01-01
    • 1970-01-01
    • 2016-11-12
    相关资源
    最近更新 更多