This is my code
@if (ViewBag.last5Articles != null)
{
List<Article> articles = ViewBag.last5Articles;
foreach (var article in articles)
{
<div class="col-md-12">
<div class="row">
<h2>@article.Title</h2>
</div>
<div class="row">
<div class="col-md-6">
<p>@article.Body</p>
</div>
</div>
</div>
}
}
I put a breakpoint on the start of the foreach loop. I can see that article is not null and it has a title and a body. But when I reach article.Body and I press F10 (Step Over) suddenly it became Null!!
"An exception of type
'System.NullReferenceException'
occurred in App_Web_ayg111kp.dll but was not handled in user code"
.
And when I finish debugging the yellow screen welcomes me with this message "Object reference not set to an instance of an object
".
Can anybody explain this problem to me please. I'm using .NET 4.5.2 and MVC 5.2
I found the answer to my (same) problem here
Try commenting out the next code line AFTER the error.
In your case, if you have
<div class="col-md-12">
<div class="row">
<h2>@article.Title</h2>
</div>
<div class="row">
<div class="col-md-6">
<p>@article.Body</p>
</div>
</div>
</div>
...more html stuff...
<p> @article.SomethingElse </p>
Try commenting out the '@article.SomethinElse' and see if it clears up the error
From link: "Some times compiler could not point on exact lines having specific kind of errors in razor view may be because it could not keep their line number in stack trace or somewhere. I have found this case with Null Reference Exception and when null is passed in Url.Content.
So it helps to check the next C# statement in razor view when you did not get any error on the line shown by stack trace."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With