NullReferenceException:对象引用未设置为对象的实例.在 foreach 循环中
本文关键字:实例 foreach 循环 对象 对象引用 设置 NullReferenceException | 更新日期: 2023-09-27 18:37:09
我的对象的实例遇到问题,它给了我一个我不明白的错误
List<Event> events = parseResponse.Deserialize<List<Event>>(_responseAsString);
ViewBag.eventss = events;
.html
<table id="eventist" border="0" cellspacing="0" cellpadding="0">
<thead>
<tr>
<th>
event_key
</th>
<th>
user_token
</th>
<th>
event_set_key
</th>
<th>
event_type
</th>
<th>
event_date
</th>
<th>
event_amount
</th>
<th>
event_location_key
</th>
<th>
event_location_name
</th>
<th>
event_location_city
</th>
<th>
event_location_state
</th>
<th>
event_location_country
</th>
<th>
event_acknowledged
</th>
</tr>
</thead>
<tbody>
<%List<StopMalaria.Models.Event> events= ViewBag.eventss;%>
<% foreach (var item in events)
{ %>
<tr>
<td>
<%: item.event_key%>
</td>
<td>
<%: item.user_token%>
</td>
<td>
<%: item.event_set_key%>
</td>
<td>
<%: item.event_type%>
</td>
<td>
<%: item.event_date%>
</td>
<td>
<%: item.event_amount%>
</td>
<td>
<%: item.event_location_key%>
</td>
<td>
<%: item.event_location_name%>
</td>
<td>
<%: item.event_location_city%>
</td>
<td>
<%: item.event_location_state%>
</td>
<td>
<%: item.event_location_country%>
</td>
<td>
<%: item.event_acknowledged%>
</td>
</tr>
<% } %>
</tbody>
</table>
所以我这样做了。 现在它说[NullReferenceException:对象引用未设置为对象的实例。 并且我的<% foreach(var item in events)
突出显示为红色。
我已经有一个包含所有元素的类
public class Event
{
public string event_key { get; set; }
public string user_token { get; set; }
public string event_set_key { get; set; }
public string event_type { get; set; }
public string event_date { get; set; }
public string event_amount { get; set; }
public string event_location_key { get; set; }
public string event_location_name { get; set; }
public string event_location_city { get; set; }
public string event_location_state { get; set; }
public string event_location_country { get; set; }
public string event_acknowledged { get; set; }
}
为您的视图添加视图模型,示例可能如下所示。此外,请在操作中使用此视图模型:
public class EventListModel
{
public EventListModel()
{
EventList = new List<Event>();
}
public string FormId { get; set; }
public string ProgramId { get; set; }
public string FormName { get; set; }
public IList<Event> EventList { get; set; }
}