How does one avoid a NullReferenceException in a foreach loop within a View when my model is null?
asp.net-mvc, foreach
Solution
If my understanding is correct your collection is null.
A collection should never be null, like you said you should return an empty collection instead and prevent your collection to be corrupted not exposing the real collection:
public IList<Employee> Employees
{
get;
private set;
}
And initialize your collection inside the constructor
this.Employees = new List<Employee>();
Problem
I get a "NullReferenceException was unhandled by user code" error with the following code in my View when I pass in a null value via my controller. There are situations where I want to pass in a null value, but I do not want an error thrown when this happens. What should I change my code to? Originally my code was: ``` @foreach (var item in Model.MyModelStuff) { <tr> <td> @Html.DisplayFor(modelItem => item.Bla.Title) </td> <tr> } ``` I have tried the following with no success: ``` @foreach (var item in Model.MyModelStuff.Where( item => item.MyModelStuff != null)) etc. . . ``` How do I change the code so that it will handle null without throwing an error? I've read I may need to be returning an empty collection of my model (?), how would I go about doing that - if it is indeed the necessary thing to do?