我尝试循环浏览列表并将内容放入viewbag中。我的问题是,当我在视图中抓取viewbag时,它只显示循环最后一次迭代的内容。关于发生了什么的任何想法?这是一个例子:
var output = new List<AirportsInACity>();
foreach (var airport in cities)
{
var temp = new AirportsInACity();
temp.airportName = airport.name
temp.aircraftList = new List<AirportAircraftTypeList>();
foreach (aircraft in airport.aircraftTypes)
{
aircraftTemp = new AirportAircraftTypeList();
aircraftTemp.aircraftType = aircraft.AircraftType.AircraftTypeModel;
aircraftTemp.seats = aircraft.Seats;
aircraftTemp.attendants = aircraft.Attendants;
temp.aircraftList.Add(aircraftTemp);
}
output.Add(temp);
var outputStats = temp.AircraftList.GroupBy(p => p.aircraftType);
foreach (var item in outputStats)
{
ViewBag.AirportName = temp.name;
ViewBag.AirportAircraftType = item.Key;
ViewBag.AircraftSeatsSum = item.Sum(p => p.seats);
}
}
ViewBag.Output = output;
return PartialView(output);
现在,让我说我有这个信息:
Airport Name: JFK
Aircraft Type: Boeing777
Total Seats: 400
Airport Name: ATL
Aircraft Type: Boeing777
Total Seats: 800
Airport Name: LAS
Aircraft Type: Boeing727
TotalSeats: 150
问题在于,在我的Viewbag中,它只抓取最后一块信息(LAS机场),但控制台正在输出所有信息。问题是什么?
以下是视图的示例:
@foreach (var item in Viewbag.Output)
{
<td>@(ViewBag.AirportName)</td>
<td>@(ViewBag.AirportAircraftType)</td>
<td>@(ViewBag.AircraftSeatsSum)</td>
}
答案 0 :(得分:0)
在ViewBag.Output
上,您有一个包含以下属性的AirportsInACity
类型列表:airportName
和aircraftList
,其中包含AirportAircraftTypeList
类型的列表。接下来,你有一个foreach
到`outputStat&#39;该设置始终是 SAME ViewBag项目。
您必须创建一个新的viewmodel,其中放置outputStats
public class AircraftViewModel
{
public string AirportName {get; set; }
public string AirportAircraftType {get; set;}
public int AircraftSeatsSum {get; set; }
}
[..]
var outputStats = temp.AircraftList.GroupBy(p => p.aircraftType);
List<AircraftViewModel> vm = new List<AircraftViewModel>();
foreach (var item in outputStats)
{
var aircraft = new AircraftViewModel();
aircraft.AirportName = temp.name;
aircraft.AirportAircraftType = item.Key;
aircraft.AircraftSeatsSum = item.Sum(p => p.seats);
vm.Add(aircraft);
}
}
ViewBag.Output = vm;
答案 1 :(得分:-1)
创建ExpandoObject并将其添加到“详细信息列表”。
示例:
控制器代码:
List<dynamic> Details = new List<dynamic>();
foreach (var item in outputStats)
{
dynamic detail;
detail = new ExpandoObject();
detail.AirportName =temp.name;
detail.AirportAircraftType = item.Key;
detail.AircraftSeatsSum =item.Sum(p => p.seats);
Details.Add(detail);
}
ViewBag.Details = Details;
查看代码:
@foreach (dynamic detail in ViewBag.Details)
{
<td>@(detail.AirportName)</td>
<td>@(detail.AirportAircraftType)</td>
<td>@(detail.AircraftSeatsSum)</td>
}