Muhammad Nasir
Muhammad Nasir

Reputation: 2204

Nullable object must have a value in MVC4

I have a Class which has an attribute which could be null or set to time date. I for this attribute i created a field of type Date time which could be null or Date time value.I am unable to check in view where date is set or not. Inside Model class I have a nullable DateTime attribute.

 public DateTime? CollectionDate { get; set; }

In my view i and to check if data is set to any value or like this.

if( Model.CollectionDate.Value!=null){
        DateTime test = Model.CollectionDate.Value;
    }

But when i load view i give me exception Nullable object must have a value. how can i check in where date is set before or not

Upvotes: 0

Views: 741

Answers (2)

davcs86
davcs86

Reputation: 3935

Use .HasValue

if( Model.CollectionDate.HasValue){
    DateTime test = Model.CollectionDate.Value;
}

also, you can set a default value with

DateTime test = Model.CollectionDate ?? DateTime.Now;

without validate if it has value.

Upvotes: 3

Gustavo
Gustavo

Reputation: 531

try

if( Model.CollectionDate.HasValue)

Upvotes: 5

Related Questions