ASP.NET中如何带默认值显示DateTime并实现日期时间选择器?
问题解决方案
问题原因分析
- 格式字符串语法错误:
WindowEnd的DisplayFormat属性中,DataFormatString写成了"0:g",缺少了必填的{0}占位符,导致MVC解析格式时出错,出现多余逗号。 - 未启用格式编辑模式:
WindowStart的格式属性被注释,且即使启用后,若未设置ApplyFormatInEditMode = true,编辑模式下不会应用指定格式。 - 表单控制器名称错误:
Html.BeginForm中控制器名称多写了Controller后缀,MVC会自动添加该后缀,导致表单可能无法正确提交。 - ViewModel缺失属性:视图中用到的
CustomerReference等属性未在ViewModel中定义,会引发编译错误。
修正代码
1. 修正ViewModel
using System; using System.ComponentModel.DataAnnotations; namespace GIO.WEB.Models { public class BookingWeb { [DataType(DataType.DateTime), Required] [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy hh:mm:ss}", ApplyFormatInEditMode = true)] public DateTime WindowStart { get; set; } [DataType(DataType.DateTime), Required] [DisplayFormat(DataFormatString = "{0:g}", ApplyFormatInEditMode = true)] public DateTime WindowEnd { get; set; } // 补充视图中用到的属性 public string CustomerReference { get; set; } public string DriverName { get; set; } public string VehicleRegPlate { get; set; } public string TrailerName { get; set; } public BookingWeb() { WindowStart = DateTime.Now.Subtract(TimeSpan.FromHours(6)); WindowEnd = DateTime.Now.AddHours(6); } } }
2. 修正视图代码
@model GIO.WEB.Models.BookingWeb @using(Html.BeginForm("SubmitBooking", "Bookings")) { <div class="form-group"> <div> @Html.LabelFor(s => s.CustomerReference) @Html.TextBoxFor(s => s.CustomerReference, new {@class = "form-control"}) </div> <div> @Html.LabelFor(s => s.WindowStart) <!-- 显式指定格式,确保默认值正确显示 --> @Html.TextBoxFor(s => s.WindowStart, "{0:dd/MM/yyyy hh:mm:ss}", new {@class = "form-control"}) </div> <div> @Html.LabelFor(s => s.WindowEnd) @Html.TextBoxFor(s => s.WindowEnd, "{0:g}", new {@class = "form-control"}) </div> <div> @Html.LabelFor(s => s.DriverName) @Html.TextBoxFor(s => s.DriverName, new {@class = "form-control"}) </div> <div> @Html.LabelFor(s => s.VehicleRegPlate) @Html.TextBoxFor(s => s.VehicleRegPlate, new {@class = "form-control"}) </div> <div> @Html.LabelFor(s => s.TrailerName) @Html.TextBoxFor(s => s.TrailerName, new {@class = "form-control"}) </div> <input type="submit" value="Generate report" /> </div> }
关键说明
- 格式字符串规范:
DataFormatString必须包含{0}占位符,代表要格式化的字段值,比如"{0:dd/MM/yyyy hh:mm:ss}"。 - 编辑模式格式启用:
ApplyFormatInEditMode = true确保输入框中显示的是指定格式的日期值,而非系统默认格式。 - 控制器名称修正:
Html.BeginForm的第二个参数只需控制器前缀(如"Bookings"),MVC会自动匹配BookingsController。 - HTML5日期选择器适配:如果需要使用原生datetime-local选择器,需将格式改为
yyyy-MM-ddTHH:mm:ss,或引入第三方日期组件(如jQuery UI Datepicker)实现自定义格式的选择器。
内容的提问来源于stack exchange,提问作者aberforth
相关产品推荐
相关产品推荐

