Reputation: 851
I am using an anonymous type to represent an object so that I can convert it into JSON format using the Json() method. Here is a sample of my code below.
The "MoviesList" variable is just a list of objects of type Objects.Movie.
var result = new List<object>();
foreach (Objects.Movie movie in MoviesList)
{
result.Add(new
{
CompletedTime = (movie.CompletedTime == null ? new Nullable<DateTime>() : movie.CompletedTime),
Genre = movie.Genre,
Title = movie.Title,
Director = movie.Director
});
}
return Json(result, JsonRequestBehavior.AllowGet);
Before, I had the code written so that the CompletedTime property in the anonymous type is equal to the CompletedTime Property in the Movie object.
However, when I ran that and there were Movie objects in MoviesList where the CompletedTime Property was null (as the movie wasn't watched and therefore not finished yet), I got a System.InvalidOperationException saying: Nullable object must have a value.
So, I tried changing it to the code I have above, and I still get the same error.
I want a null value to be there if the movie has not been finished yet but I am getting this error. Is there any way to fix this or should I try a different approach?
movie.CompletedTime is of type "DateTime?"
EDIT: Whenever I debug this code, the debugger goes into the foreach loop, and iterates. However, when it is on an iteration where an Objects.Movie object contains the property CompletedTime (movie.CompletedTime) where the value is null, it catches an error and returns me to the JsonResult type method that called the above code and returns the caught error
StackTrace is below:
at System.Nullable`1.get_Value()
at WebService.Controllers.DataController.GenerateMovieList(DateTime date, String classID) in C:\WebService\Controllers\DataController.cs:line 212
at WebService.Controllers.DataController.GetMovieList(String Date, String ClassID) in C:\WebService\Controllers\DataController.cs:line 133
Upvotes: 2
Views: 1593
Reputation: 62213
After looking at your stack trace it does look like you are doing a .Value on a nullable object that does not have a value. Try changing that one line to this:
CompletedTime = movie.CompletedTime, // just pass in the nullable object as is
It would also help to include the complete methods as you have them if this is not the answer.
Upvotes: 2