1

I'm just trying to show some values in the view from the database. But I got the error : "Object reference not set to an instance of an object"

Here my View (copyPasta from VS tool) :

@model List<Projet.Models.UserProfile>

@{
ViewBag.Title = "Administration - Index";
}

<h2>Administration - Users management</h2>
<p>
@Html.ActionLink("Users management", "Index") |
@Html.ActionLink("Roles management", "RoleIndex", "Account") |
@Html.ActionLink("Events management", "Create")
</p>
 <p>
@Html.ActionLink("Create new user", "AddUser", "Account")
</p>
<table>
<tr>
    <th>
        Username
    </th>
    <th>
        Email
    </th>
    <th>
        First name
    </th>
    <th>
        Last name
    </th>
    <th></th>
</tr>

@foreach (var item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.UserName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Email)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Fname)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Lname)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id = item.UserName }) |
        </td>
    </tr>
}

</table>

So on the view I got all the values from @Html.DisplayFor but the error come from @Html.ActionLink("Edit", "Edit", new { id = item.UserName }) it seems to be item.UserName = null. But how it is possible because he give me the values in the Html.DisplayFor just above...

If needed my Controller code :

    public ActionResult FriendsIndex()
    {
        db.Friends.Select(a => a.Friend).ToList();
        int UserId = WebSecurity.GetUserId(User.Identity.Name);
        List<int> FriendsList = db.Friends.Where(a => a.FriendOf == UserId).Select(a => a.Friend).ToList();
        List<UserProfile> FriendsListStr = new List<UserProfile>();

        for (int i = 0; i < FriendsList.Count; i++) 
        {
            FriendsListStr.Add(db.UserProfiles.Find(FriendsList[i]));
        }

        return View(FriendsListStr);
    }
Konstantin Dinev
  • 30,746
  • 13
  • 64
  • 91
  • Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders May 29 '15 at 05:55
  • Debug your view and see if it is indeed null. Note that `DisplayFor` takes an expression and likely can work fine even if item is null. In general there is no way to look at such lambda expression and know if it is called immediately, called later or not called at all but used to do some fancy "reflection"-like work - obvious sample LINQ -to-SQL. – Alexei Levenkov May 29 '15 at 05:57
  • It seem to be solved, I was debug the View and add some conditions (Model != null, item != null) and the error disappears, it's really strange ! – PokeR StaRR May 29 '15 at 06:45

0 Answers0