AlexGH AlexGH - 2 years ago 92
HTML Question

Average of null list throws Exception on Razor View

I put directly on a Razor View a Linq Query to get the age average of a list of people... When that list is null it throws a Null Reference Exception... The code works great when the list is not null..

This is the code snippet on the Razor View(The Exception is thrown from here):

<label> Age average:</label>@Model.DefaultIfEmpty().Average(p => p.Age)

And this is the code snippet where the list is created on the Controller Class(the Exception is thrown when there is not coincidence, I mean when the list is null...):

public ActionResult Index(int? age, string name)
var people = db.People.ToList();
if (age != null && !string.IsNullOrEmpty(name))
people = db.People.Where(x => x.Age >= age && x.Name.Contains(name)).ToList();
else if (age != null && string.IsNullOrEmpty(name))
people = db.People.Where(x => x.Age >= age).ToList();
else if (age == null && !string.IsNullOrEmpty(name))
people = db.People.Where(x => x.Name.Contains(name)).ToList();
return View(people);

How could I set to 0 the default value of average in the Razor View if the list is null??
I've been trying with coalescing operator ?? but I'm not sure of how to do this, is inside a Razor View..

Answer Source

Your model is not null - its just an empty collection. You could use

@Model.Select(x => x.Age).DefaultIfEmpty(0).Average();

which will return 0.0 if the collection is empty. But note that this code really belongs in your controller, not the view (and pass the result of the query to the view using a view model property (or ViewBag)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download