繁体   English   中英

在Model中为DateTime使用数据注释

[英]Using Data annotation in Model for DateTime

我使用下面的代码,弹出日期日历在我的Razor视图

模型

[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)]

我收到格式异常?

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

要生成HTML-5 datetimepicker,您需要呈现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]属性或ApplyFormatInEditMode = true的财产[DisplayFormat]属性,因为它们只适用于EditorFor()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM