Note that there are some explanatory texts on larger screens.

plurals
  1. PONullReferenceException in MVC3 Controller
    primarykey
    data
    text
    <p>I'm playing around with MVC3, trying to create small test projects which simulate problems that I anticipate I will encounter in a larger project I'm migrating from PHP. I keep getting a "NullReferenceException" on instantiating the "model" variable in the project with the elements below:</p> <p>Model:</p> <pre><code>public class MainModel { public IEnumerable&lt;Chemical&gt; chemicals { get; set; } } public class Chemical { public int ChemicalId { get; set; } public string Name { get; set; } public virtual ICollection&lt;Hazard&gt; Hazards { get; set; } } public class Hazard { public int HazardId { get; set; } public string Description { get; set; } public virtual ICollection&lt;Chemical&gt; Chemicals { get; set; } } </code></pre> <p>Controller:</p> <pre><code>public class MainController : Controller { public ActionResult Index() { var h1 = new Hazard { HazardId = 1, Description = "Flammable" }; var h2 = new Hazard { HazardId = 2, Description = "Carcinogen" }; var h3 = new Hazard { HazardId = 3, Description = "Water Reactive" }; var model = new [] { new Chemical { ChemicalId = 1, Name = "Benzene", Hazards = {h1, h2}}, new Chemical { ChemicalId = 2, Name = "Sodium", Hazards = { h3 } }, new Chemical { ChemicalId = 3, Name = "Chloroform", Hazards = { h2 } }, new Chemical { ChemicalId = 4, Name = "Water" } }; //NULL EXCEPTION THROWN HERE return View(model); } } </code></pre> <p>So, I have two questions:</p> <ol> <li>Why do I keep getting the NullReferenceException, and how could it be fixed?</li> <li>In writing this code, I used this <a href="https://stackoverflow.com/questions/4872192/checkboxlist-in-mvc3-0">StackOverFlow Page</a> as a starting point. Why is this okay, but what I wrote is not? Granted, I didn't test this code, but the author seems very competent.</li> </ol> <p>Thanks! </p>
    singulars
    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.
 

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