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

前端 未结 1 712
孤独总比滥情好
孤独总比滥情好 2021-01-25 21:07

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 FromD         


        
相关标签:
1条回答
  • 2021-01-25 21:30

    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)

    0 讨论(0)
提交回复
热议问题