Matthias
Matthias

Reputation: 13414

NullReferenceException Include LINQ expression MVC3

Following code in a Details.cshtml page:

 @{
            @Html.Raw(" | ");
            for (int i = 0; i < Model.Payments.Count; i++)
            {
                @Html.Raw("<a href=../../Payment/Details/" + Model.ID + "/" + Model.Payments.ElementAt(i).accountID + ">" + Model.Payments.ElementAt(i).Account.landIOC + "</a>");           
                @Html.Raw(" | ");
            }
        }

Model.Payments.ElementAt(i).Account is always NULL for some reason, although a payment always has exactly one account AND we include Account in our LINQ expression (PaymentController):

_erasDb.Payments.Include("Account").Include("Event").Where(...)

We have no idea why Account is NULL. For the complete code, see:

http://pastebin.com/Yf1JDsMF

Upvotes: 2

Views: 321

Answers (2)

Alexander Taran
Alexander Taran

Reputation: 6725

Questions: what EF scheme are you using db, model or code first?
in your view you can use <text> | </text> to replace Html.Raw(" | ");
Again your link generation strategy is a bit wired. Those links, i suppose, have corresponding actions, so there must be routes and you can use Html.ActionLink.
And iterating with a foreach(var m in Model.Payments) could make your code a bit more prety:

@{
 <text> |
  @foreach(var m in Model.Payments){
    <text>
    @Html.ActionLink(m.Account.landIOC,"Details","Account",new{Id = m.ID, AccountId= m.AccountID}) |
    </text>
  }
</text>
}

Now this could be a starting point.

Upvotes: 2

Marc Gravell
Marc Gravell

Reputation: 1062550

Multiple calls to ElementAt is pretty inefficient. Just switch to foreach - it should fix ElementAt returning null, be more efficient, and simpler.

Also, why not just:

<text> | </text>
foreach(var payment in Model.Payments)
{
    <a href=../../Payment/Details/@Model.ID/@payment.accountID">@payment.Account.landIOC</a>          
    <text> | </text>
}

If you are using lots of @Html.Raw(...), you're probably missing a trick... in particular, you stand a good chance of opening xss holes if you use too much .Raw.

Upvotes: 4

Related Questions