System.NullReferenceException
means that an instance in your code was
null
. You forgot to perform a
new
on the object and passed the default value in the code.
There are multiple ways in which you can prevent this error, the most basic and recommended approach is to create the instances properly.
var obj = new Type();
Where exactly you are getting the error starts from the
foreach
loop in your code and goes all the way down. From your question, I can tell perhaps this is null,
@foreach (var item in Model.ListOfProducts)
You can fix the problem with this:
@if(Model.ListOfProducts != null) {
foreach (...) { }
} else {
<p>The product list is null. Check the controller where it is being passed.</p>
}
But this does not solve the problem, does it? It will merely prevent the error from happening on the runtime. The good solution is to make sure that
Model
receives the value in
ListOfProducts
from the controller. You need to check if you are passing a
null
to
View()
function call.
Here are a few of my previous answers that discuss this problem and its solution in different contexts:
Null reference exception[
^]
Problem with 'Null Reference' Error while creating Class instances[
^]
how to handle null reference and out of bound exceptions[
^]