[英]NullReferenceException c# in controller
I get a NullReferenceException
when try to run a view. 尝试运行视图时出现
NullReferenceException
。 I don't see the code that cause this problem. 我没有看到导致此问题的代码。 Can someone explain the problem?
有人可以解释这个问题吗? thanks
谢谢
This is the Model class: 这是Model类:
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: 具有NullRef异常的控制器:
This line cause the problem. 这条线导致了这个问题。
IEnumerable materialen = catalogus.VindAlleMaterialen().OrderBy(m => m.Naam).ToList();
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. 您的默认构造函数
public CatalogusController
不会创建catalogus
实例。 When you then execute catalogus.VindAlleMaterialen().OrderBy(m => m.Naam).ToList();
然后执行
catalogus.VindAlleMaterialen().OrderBy(m => m.Naam).ToList();
it results in a NullReferenceException because catalogus
is null. 它导致NullReferenceException,因为
catalogus
为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. 看起来有人可以在不传入ICatalogus对象的情况下构建CatalogusController。 This will cause a NullReferenceException when someone calls
controller.Index()
: 当有人调用
controller.Index()
时,这将导致NullReferenceException:
// Create a controller object using the default constructor
CatalogusController controller = new CatalogusController();
// this causes a NullReferenceException because controller.catalogus is null
controller.Index();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.