You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core MVC中预约日期显示异常问题求助

解决ASP.NET Core MVC中预约日期显示为01.01.0001的问题

问题根源

显示01.01.0001 00:00是因为DateTime类型的默认值,说明Create页面提交时,预约日期没有正确绑定到模型属性,导致数据库存入的是默认值,而非用户选择的日期。

分步解决方案

1. 检查Create视图的日期输入控件绑定

确保Create页面的日期输入控件正确关联到CustomerCarDateDayTime属性,且格式兼容:

<!-- Views/Customers/Create.cshtml 中的日期输入部分 -->
<div class="form-group">
    @Html.LabelFor(model => model.CustomerCarDateDayTime, "预约日期时间", new { @class = "control-label" })
    @Html.EditorFor(model => model.CustomerCarDateDayTime, new { 
        htmlAttributes = new { @class = "form-control", type = "datetime-local" } 
    })
    @Html.ValidationMessageFor(model => model.CustomerCarDateDayTime, "", new { @class = "text-danger" })
</div>
  • datetime-local类型的输入控件要求格式为yyyy-MM-ddTHH:mm,需确保模型的DisplayFormat在编辑模式下兼容,可调整模型属性:
    // Models/Customers.cs
    [DataType(DataType.DateTime)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-ddTHH:mm}")]
    public DateTime CustomerCarDateDayTime { get; set; }
    

2. 检查Create动作方法的模型绑定

确认POST请求的Create方法正确接收并保存日期值,避免遗漏绑定字段:

// CustomersController.cs 的POST Create方法
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,CustomerName,CustomerCarDateDayTime")] Customer customer)
{
    if (ModelState.IsValid)
    {
        _context.Add(customer);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }
    return View(customer);
}
  • 重点检查Bind特性中是否包含CustomerCarDateDayTime,如果遗漏,该属性会使用默认值存入数据库。

3. 修正Index页面的日期显示(确保数据库已有正确值时)

如果数据库中已存在正确的预约日期,可直接在视图中强制格式化:

<!-- Views/Customers/Index.cshtml 中的日期列 -->
<td>
    @item.CustomerCarDateDayTime.ToString("dd/MM/yyyy HH:mm")
</td>

或者调整模型的DisplayFormat,让DisplayFor自动应用格式:

// Models/Customers.cs
[DataType(DataType.DateTime)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy HH:mm}", ApplyFormatInEditMode = true)]
public DateTime CustomerCarDateDayTime { get; set; }

4. 验证数据库数据

直接查看数据库的Customers表,确认CustomerCarDateDayTime字段是否为用户选择的日期:

  • 如果是默认值,回到步骤1、2排查绑定问题;
  • 如果已有正确日期,仅需调整显示格式即可。

内容的提问来源于stack exchange,提问作者Jackie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 14:05:37