Bootstrap Datepicker:无法隐式转换类型"System.DateTime?"到"System.DateTime".存在显式转换(您是否缺少演员表?) [英] Bootstrap Datepicker: Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists (are you missing a cast?)

查看:108
本文介绍了Bootstrap Datepicker:无法隐式转换类型"System.DateTime?"到"System.DateTime".存在显式转换(您是否缺少演员表?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是这里的新手.我在这里经历了类似的问题,但没有一个有帮助.我的ViewModel中有以下内容:

I am a newbie here. I have gone through similar questions here but none of them helped. I have the following in my ViewModel:

public DateTime FromDate { get; set; }

public DateTime ToDate { get; set; }

运行代码时,在GET Method之后的View中,我得到的默认日期为:01/01/0001,换句话说,为null/默认值.我在线搜索,发现需要将这些字段设置为nullable.因此,我将上面的代码更改为:

When I run the code, in the View after GET Method, I am getting the default dates as: 01/01/0001, in other words, null/default value. I searched online and found out that I need to make these fields nullable. Therefore, I changed the above code to:

public DateTime? FromDate { get; set; }

public DateTime? ToDate { get; set; }

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

Upon changing, I am getting the following error for both FromDate and ToDate:

无法隐式转换类型'System.DateTime?'到"System.DateTime".存在显式转换(您是否缺少演员表?)

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的不可为空的属性,但是视图模型具有等效的可为空的属性.

The issue is that your data model has non-nullable properties for FromDate and ToDate, but the view model has equivalent nullable properties.

由于值可能为null,因此无法将DateTime?明确转换为DateTime.

You cannot explicitely convert a DateTime? to a DateTime because the value may be null.

如果视图模型属性装饰有[Required]属性,并且您在映射前已选中ModelState.Isvalid(即您知道该属性具有值),则可以使用

If your view model properties are decorated with the [Required] attribute and you have checked ModelState.Isvalid before mapping (i.e. you know the property has a value), then you can use

history.FromDate = locationsViewModel.FromDate.Value;

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

If not, then the property could be null, in which case you need to use

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

将数据模型值设置为1/1/0001(默认值来自DateTime)

which will set the data model value to 1/1/0001 (the default value fro DateTime)

这篇关于Bootstrap Datepicker:无法隐式转换类型"System.DateTime?"到"System.DateTime".存在显式转换(您是否缺少演员表?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆