ASPCoder1450
ASPCoder1450

Reputation: 1651

ViewBag throws NullReferenceException (Object Not Sent to Instance)

ViewBag Data throws this exception and Im not sure why? The exception errors in the View Class on the line containing ViewBag.Data. Any help would be greatly appreciated!

<table>
<tr>
    <th>Response Text</th>
    <th>Date & Time of Update</th>
    <th>Username</th>
</tr>

@foreach (OfficiumWebApp.Models.ResponseViewModel item in ViewBag.Data)
{
    <tr>
        <td>@item.ResponseText</td>
        <td>
        <td>@item.DateTimeOfUpdate</td>
        <td>
        <td>@item.Username</td>
        <td>
    </tr>
}

Here is the method in my controller:

   [Authorize(Roles = "Customer")]
    public ActionResult Index()
    {
        var yyy = (from a in db.Responses select new ResponseViewModel {ResponseText = a.ResponseText, DateTimeOfUpdate = a.DateTimeOfUpdate.ToString(), Username = a.UserName});
        ViewBag.Data = yyy;
        var LogResponses = from b in db.Responses where b.LogID == LogID select b;
        return View(LogResponses.ToList());
    }

Upvotes: 2

Views: 3158

Answers (1)

Lin
Lin

Reputation: 15188

You need to add a null value check for ViewBag.Data in your view like below:

@if (ViewBag.Data != null)
{
   foreach (OfficiumWebApp.Models.ResponseViewModel item in ViewBag.Data)
   {
     <tr>
        <td>@item.ResponseText</td>
        <td>
        <td>@item.DateTimeOfUpdate</td>
        <td>
        <td>@item.Username</td>
        <td>
     </tr>
   }
}

Upvotes: 3

Related Questions