Note that there are some explanatory texts on larger screens.

plurals
  1. POMVC 3 accept null foreach in the viewModel
    primarykey
    data
    text
    <p>I have a page where users can enter their state information and then a list of other users come back within the state. I am using a <code>foreach</code> loop.</p> <p>Some of the states have 0 users, which then leads me to get an error: <strong>Object reference not set to an instance of an object</strong>. How can I get past that error? The particular model I'm using is called Profiles.</p> <p>The Model:</p> <pre><code>public class homepage { public List&lt;profile&gt; profile { get; set; } public PagedList.IPagedList&lt;Article&gt; article { get; set; } } </code></pre> <p>The Controller:</p> <pre><code>public ActionResult Index() { HttpCookie mypreference = Request.Cookies["cook"]; if (mypreference == null) { ViewData["mypreference"] = "Enter your zipcode above to get more detailed information"; var tyi = (from s in db.profiles.OrderByDescending(s =&gt; s.profileID).Take(5) select s).ToList(); } else { ViewData["mypreference"] = mypreference["name"]; string se = (string)ViewData["mypreference"]; var tyi = (from s in db.profiles.OrderByDescending(s =&gt; s.profileID).Take(5) where se==s.state select s).ToList(); } return View(); } </code></pre> <p>The View:</p> <pre><code>@if (Model.profile != null) { foreach (var item in Model.profile) { @item.city } } </code></pre> <p>When I get the <strong>Object reference not set to an instance of an object</strong> error, the line <code>@if (Model.profile != null)</code> is highlighted, so I tried to do this:</p> <pre><code>public List&lt;profile&gt;? profile { get; set; } </code></pre> <p>But it didn't work. Any ideas of how to accept an empty Model in a foreach or just skip the code at runtime?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload