简体   繁体   中英

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());
    }

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>
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM