An exception of type "System.NullReferenceException" occurred in App_Web _ ***. Dll

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 at the beginning of the foreach loop. I see that the article is not null and has a title and a body. But when I get to the .Body article and I press F10 (Step Over), all of a sudden it becomes 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 greets me with this message "Object reference not set to object instance".

Can someone explain this problem to me please. I am using .NET 4.5.2 and MVC 5.2

+3


source to share


1 answer


I found the answer to my (same) problem here

Try commenting out the following line of code 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 "@ article.SomethinElse" and see if it clears the error

From the link: "For a while the compiler could not point to exact lines with certain types of errors in the razor view, maybe because it could not store its line number in the stack trace or somewhere. I found this case with Null Reference Exception and when null is passed to Url.content.

So it helps to test the following C # statement in razor mode when you didn't get any errors on the line displayed by the stack trace. "

+3


source







All Articles