How to avoid a NullReferenceException in a foreach loop in a view when my model is zero?

I get the error "Error NullReferenceException was unhandled user code" with the following code in my view when I pass a null value through my controller. There are situations when I want to pass a null value, but I do not want an error to occur when this happens. What should I change my code?

My code was originally:

@foreach (var item in Model.MyModelStuff)
{
    <tr>
        <td>
                @Html.DisplayFor(modelItem => item.Bla.Title)
        </td>
    <tr>
}

I tried the following without success:

@foreach (var item in Model.MyModelStuff.Where( item => item.MyModelStuff != null))
etc. . . 

How do I change the code so that it processes null without causing an error? I read, maybe I will need to return an empty collection of my model (?), How would I do it - if it is really necessary?

+3
source share
2

, .

, , , :

public IList<Employee> Employees
{
    get; 
    private set;
}

this.Employees = new List<Employee>();
+6

, , null - . , if:

@if (Model != null) {
    foreach (var item in Model.MyModelStuff)
    {
        <tr>
            <td>
                    @Html.DisplayFor(modelItem => item.Bla.Title)
            </td>
        <tr>
    }
}
+6

All Articles