简体   繁体   中英

NullReferenceException c# in controller

I get a NullReferenceException when try to run a view. I don't see the code that cause this problem. Can someone explain the problem? thanks

This is the Model class:

public class Catalogus: ICatalogus
{
    private readonly DbSet<Materiaal> materialen;
    private IEnumerable<Materiaal> materialenTest;
    private Firma firma;

    public Catalogus()
    {
        firma = new Firma("hh", "lol@gmail.com");
        materialenTest = new Materiaal[] { new Materiaal(5, 0, "1", "test", "test", "ts", firma, "wereldbol", "wereldbol", "lol", 0, true) };
    }

    public IEnumerable<Materiaal> VindAlleMaterialen()
    {
        return materialenTest.OrderBy(m => m.Naam);
    }

    public IEnumerable<Materiaal> ZoekOpTrefwoord(string trefwoord)
    {
        IEnumerable<Materiaal> gefilterdMaterialen = materialenTest.Where(mat => mat.GetType().GetProperty("naam").GetValue(this).Equals(trefwoord));

        return gefilterdMaterialen;
    }
} 

The controller with the NullRef exception:

This line cause the problem.

IEnumerable materialen = catalogus.VindAlleMaterialen().OrderBy(m => m.Naam).ToList();

public class CatalogusController : Controller
{
    private ICatalogus catalogus;

    public CatalogusController() { }

    public CatalogusController(ICatalogus catalogus)
    {
        this.catalogus = catalogus;
    }

    public ActionResult Index()
    {
        IEnumerable<Materiaal> materialen = catalogus.VindAlleMaterialen().OrderBy(m => m.Naam).ToList();

        return View(materialen);
    }
}

Your default constructor public CatalogusController does not create an catalogus instance. When you then execute catalogus.VindAlleMaterialen().OrderBy(m => m.Naam).ToList(); it results in a NullReferenceException because catalogus is null.

If your overloaded constructor IS being called (probably not the case) you should validate the incoming parameter.

public CatalogusController(ICatalogus catalogus)
{
    if(catalogus == null) throw new ArgumentNullException("catalogus");
    this.catalogus = catalogus;
}

It looks like someone could contruct a CatalogusController without passing in an ICatalogus object. This will cause a NullReferenceException when someone calls controller.Index() :

// Create a controller object using the default constructor
CatalogusController controller = new CatalogusController();

// this causes a NullReferenceException because controller.catalogus is null
controller.Index();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM