-->

Bootstrap Datepicker: Cannot implicitly convert ty

2019-03-04 07:35发布

问题:

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)