【发布时间】:2015-04-14 16:43:35
【问题描述】:
我创建了一个空白的 MVC5 控制器,我被告知要这样做,在创建带有多路连接子句的 select 语句后,我尝试将选定的信息传递到视图中,但在加载视图时它会因以下错误而崩溃:
“传递到字典中的模型项的类型为'System.Collections.Generic.List1[<>f__AnonymousType65[System.DateTime,System.TimeSpan,System.String,System.Int32,System.String]]',但是这个字典需要“System.Collections.Generic.IEnumerable`1[snBusService04.Models.trip]”类型的模型项。"
这是我的索引视图代码
public ActionResult Index(string busRouteCode)
{
var tripInfo = "";
if (busRouteCode != null)
{
HttpCookie busRouteCodeCookie = new HttpCookie("busRouteCodeCookie");
busRouteCodeCookie.Value = busRouteCode;
busRouteCodeCookie.Expires = DateTime.Now.AddHours(1);
Response.Cookies.Add(busRouteCodeCookie);
}
else if (Request.Cookies["busRouteCodeCookie"] != null )
{
tripInfo = Request.Cookies["busRouteCodeCookie"].Value;
}
else
{
TempData["message"] = "Please select a bus route";
return RedirectToAction("Index", "snBusRoutes");
}
var tripQuery = from br in db.busRoutes
join rs in db.routeSchedules on br.busRouteCode equals rs.busRouteCode
join t in db.trips on rs.routeScheduleId equals t.routeScheduleId
join d in db.drivers on t.driverId equals d.driverId
join b in db.buses on t.busId equals b.busId
// where br.busRouteCode == busRouteCode
select new
{
t.tripDate,
rs.startTime,
d.fullName,
b.busNumber,
t.comments
};
var queryResult = tripQuery.AsEnumerable()
.Select(t => new
{
t.tripDate,
t.startTime,
t.fullName,
t.busNumber,
t.comments
});
return View(queryResult.ToList());
}
查看代码如下:
@model IEnumerable<snBusService04.Models.trip>
@{
ViewBag.Title = "Monitored Trip Information for " + Request.Cookies["busRouteCodeCookie"].Value;
}
<h2>@ViewBag.Title</h2>
<h3>@TempData["message"]</h3>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.tripDate)
</th>
<th>
@Html.DisplayNameFor(model => model.startTime)
</th>
<th>
@Html.DisplayNameFor(model => model.fullName)
</th>
<th>
@Html.DisplayNameFor(model => model.busNumber)
</th>
<th>
@Html.DisplayNameFor(model => model.comments)
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.tripDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.startTime)
</td>
<td>
@Html.DisplayFor(modelItem => item.fullName)
</td>
<td>
@Html.DisplayFor(modelItem => item.busNumber)
</td>
<td>
@Html.DisplayFor(modelItem => item.comments)
</td>
</tr>
}
</table>
【问题讨论】:
标签: c# asp.net asp.net-mvc linq asp.net-mvc-5