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

使用jQuery设置Time字段值无效,提交后引发SqlDateTime溢出错误

解决ASP.NET表单提交DateTime字段为null的问题

问题原因

你用toLocaleString()生成的本地化日期字符串,ASP.NET模型绑定无法正确解析为DateTime类型,导致Time字段绑定失败为null,触发数据库的SqlDateTime overflow错误(数据库要求该字段必须在指定时间范围内,null不符合要求)。

解决方案

方案一:后端自动赋值(推荐,更安全)

完全不需要前端处理时间,在控制器的提交Action中直接给模型的Time字段赋值,避免前端格式问题和时间篡改:

[HttpPost]
public IActionResult AskQuestion(QuestionModel model)
{
    if (ModelState.IsValid)
    {
        // 推荐用UTC时间避免时区问题,也可使用DateTime.Now
        model.Time = DateTime.UtcNow;
        _yourDbContext.Questions.Add(model);
        _yourDbContext.SaveChanges();
        return RedirectToAction("QuestionList");
    }
    return View(model);
}

方案二:前端传递可解析的ISO格式时间

如果必须前端传递时间,修改前端代码,传递ASP.NET能正确解析的ISO格式字符串:

  1. 修改表单中的时间输入框为隐藏类型(用户无需可见):
<input type="hidden" id="question_time" asp-for="Time"/>
  1. 调整jQuery提交事件的代码,使用toISOString()生成标准格式:
$('#question_form').submit(function(){
    let currdate = new Date();
    // ISO格式字符串可被ASP.NET直接解析为DateTime
    $('#question_time').val(currdate.toISOString());
    return true;
})

额外检查点

  • 确保模型类中Time字段定义为非可空的DateTime(如果数据库字段必填):
public class QuestionModel
{
    // 其他字段...
    [Required]
    public DateTime Time { get; set; }
}
  • 避免使用toLocaleString()这类本地化格式,不同地区生成的字符串格式不同,模型绑定大概率解析失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 23:18:42