【发布时间】:2018-06-27 15:20:31
【问题描述】:
我想使用引导日期时间选择器将日期发送到控制器,但出现错误
参数字典包含参数“日期”的空条目 方法的不可为空类型“System.DateTime”
这是我的模型类
public class Slot
{
public DateTime DateSlots { get; set; }
public DateTime Starttime { get; set; }
public DateTime EndTime { get; set; }
}
控制器
[httPost]
public ActionResult Createslots(string startTime, string endTime, DateTime date)
{
using (MYDb db = new MYDb())
{
Slot obj = new Slot();
obj.Starttime = Convert.ToDateTime(startTime);
obj.EndTime = Convert.ToDateTime(endTime);
obj.DateSlots = date;
db.Slots.Add(obj);
db.SaveChanges();
}
return View();
}
// my Action
public ActionResult Createslots()
{
return View();
}
查看
@using (Html.BeginForm("Createslots", "slot", FormMethod.Post))
{
<div class="col-sm-6 form-group">
@Html.LabelFor(model => model.DateSlots )
@Html.EditorFor(model => model.DateSlots , new { htmlAttributes = new { @class = "form-control" } })
</div>
<div class="col-sm-6 form-group">
@Html.LabelFor(model => model.Starttime)
@Html.EditorFor(model => model.Starttime, new { htmlAttributes = new { @class = "form-control" } })
</div>
<div class="col-sm-6 form-group">
@Html.LabelFor(model => model.EndTime)
@Html.EditorFor(model => model.EndTime, new { htmlAttributes = new { @class = "form-control" } })
</div>
<input type="submit" class="btn text-center" value="Submit" style="background: rgb(15, 94, 125);" />
}
这里是前端 Img
开始时间和结束时间我很容易得到,但是当我尝试使用 Date 然后得到这个 错误类型
参数字典包含参数“日期”的空条目 meth 的不可为空类型“System.DateTime”
注意,我也尝试在日期存储为 null 的情况下为 null
public ActionResult Createslots(string startTime, string endTime, DateTime ? date)
{
}
【问题讨论】:
-
我发现在处理日期时,将它们视为字符串然后在后端或插入数据库时将它们转换为 DateTime 会更容易。由于您的 ActionResult 需要字符串作为开始和结束,为什么不将所有三个模型属性都设为字符串,因为字符串可以作为空值传递?或者,如果您仍想在模型中使用 DateTime 对象,请将相应的模型属性更改为 Nullable Datetime
-
@RyanWilson 我尝试 tis 但收到此错误将 datetime2 数据类型转换为 datetime 数据类型导致值超出范围。声明已终止。
-
@zubairzubairgone 听起来像是将日期时间传递给 sql 的问题,(stackoverflow.com/questions/1331779/…)
-
@RyanWilson “我发现在处理日期时,将它们视为字符串更容易,然后在后端或插入数据库时将它们转换为 DateTime”......这只会让在流程的早期验证模型,因为日期解析必须手动进行。这没有任何优势。 MVC 可以将请求中提交的字符串(当然,它们在传输时始终是字符串)解析为 Dates 没问题,只要提供的字符串格式有效。
标签: c# asp.net-mvc entity-framework