dtjmsy
dtjmsy

Reputation: 2752

asp.net mvc 3 view looping through model with foreach

I am having a view with tied to a model:

@model IEnumerable<AJA.Models.DB.Article>

all I want to do is to loop through the model to do some logic:

@foreach (var item in Model)
{
    var article = item.article1;
    if (article.Length > 500)
    {
        article = article.Substring(0, 500) + "...";
    }

However, when I execute the View, error:

exception: System.NullReferenceException: The reference of the object is not defined 
to an instance of the object.

If I do @Html.DisplayFor(modelItem => item.article1) alone, I get the article OK, but I want to do business logic beforehand.

What' s wrong with it ?

Upvotes: 1

Views: 10774

Answers (1)

Only Bolivian Here
Only Bolivian Here

Reputation: 36733

First off in your View, triple check to make sure that you are using your ViewModel correctly.

Something like this should be at the top of your View:

@model IEnumerable<AJA.Models.DB.Article>

Set a breakpoint in your controller and use F10 to drill down all the way to your View, you will be able to inspect the objects in your View's foreach loop.

Somewhere along the line an object is null where you expect it to have something. Figure out what that object is.

@foreach (var item in Model)
{
    var article = item.article1; //article1 may be null. Check it!
    if (article.Length > 500)
    {
        article = article.Substring(0, 500) + "...";
    }
}

Upvotes: 3

Related Questions