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

荒凉一梦 提交于 2019-12-02 20:26:13

问题


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; }

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; }

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

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

What to do?

Edit:

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

    return RedirectToAction("Details");
}

回答1:


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

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

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;

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

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

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



来源:https://stackoverflow.com/questions/49417764/bootstrap-datepicker-cannot-implicitly-convert-type-system-datetime-to-syst

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!