我正在处理这个ASP.NET Core MVC
项目,当我收到此错误时,我正在尝试将值从form
保存到Database
中:
无法将类型"System.DateTime?"隐式转换为"System.DateTime"。存在显式转换(您是否缺少强制转换?
我在"视图模型"中通过以下方式使用 ?
nullable
FromDate
和ToDate
设置为:
视图模型:
public class ILViewModel
{
...
...
public DateTime? FromDate { get; set; }
public DateTime? ToDate { get; set; }
}
在Controller - POST Method
中,我通过以下方式向Database
添加值:
控制器:
if (ModelState.IsValid)
{
...
historyObj.FromDate = locationsHistoryVM.FromDate;
historyObj.ToDate = locationsHistoryVM.ToDate;
}
怎么办?
您需要从可为空的对象中获取值。 那么你不会得到错误
if (ModelState.IsValid)
{
...
historyObj.FromDate = locationsHistoryVM.FromDate.Value;
historyObj.ToDate = locationsHistoryVM.ToDate.Value;
}