Bootstrap 日期选择器:无法将类型 'System.DateTime?' 隐式转换为 'System.DateTime'。存在显式转换(您是否缺少转换?)

Bootstrap Datepicker: Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists (are you missing a cast?)

我是这里的新手。我在这里经历过类似的问题,但其中 none 帮助了我。我的 ViewModel 中有以下内容:

public DateTime FromDate { get; set; }

public DateTime ToDate { get; set; }

当我 运行 代码时,在 GET Method 之后的 View 中,我得到的默认日期为:01/01/0001,换句话说,null/默认值。我在网上搜索了一下,发现我需要制作这些字段nullable。因此,我将上面的代码改为:

public DateTime? FromDate { get; set; }

public DateTime? ToDate { get; set; }

更改后,FromDateToDate 均出现以下错误:

Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists (are you missing a cast?)

怎么办?

编辑:

[HttpPost]
public IActionResult Locate(...)
{
    InventoryHistory history = new InventoryHistory();
    ...
    ...
    history.FromDate = locationsViewModel.FromDate;
    history.ToDate = locationsViewModel.ToDate;
    ...
    ...
    _context.Add(history);
    _context.SaveChanges();

    return RedirectToAction("Details");
}

问题是您的数据模型具有 FromDateToDate 的 non-nullable 属性,但视图模型具有等效的可为 null 的属性。

您不能明确地将 DateTime? 转换为 DateTime,因为值可能是 null.

如果您的视图模型属性使用 [Required] 属性修饰,并且您在映射之前检查了 ModelState.Isvalid(即您知道 属性 有一个值),那么您可以使用

history.FromDate = locationsViewModel.FromDate.Value;

如果不是,则 属性 可能是 null,在这种情况下,您需要使用

history.FromDate = locationsViewModel.FromDate.GetValueOrDefault();

这会将数据模型值设置为 1/1/0001DateTime 的默认值)