【发布时间】:2020-07-10 15:24:50
【问题描述】:
我正在创建一个表,它将显示我的 SQL 数据库中的某些列。我收到了错误
InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'System.Collections.Generic.List, but this ViewDataDictionary instance requires a model item of type 'System.Collections.Generic.IEnumerable
我尝试过运行原始 sql 查询(使用 .FromSqlRaw),但在我看来它返回了一个空模型值。我了解该错误,并且无法将我的查询设置为列表并返回 IEnumerable,但我没有发现在线成功。请让我知道我可以改进的地方。谢谢!
我的观点
@model IEnumerable<MyApp.Models.BookModel>
<table>
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.BookName)
</th>
<th>
@Html.DisplayNameFor(model => model.Author)
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.BookName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Author)
</td>
</tr>
}
</tbody>
</table>
我的控制器
[HttpGet("[action]")]
[Route("/Books/Index")]
public async Task<IActionResult> Index()
{
try
{
var data = _context.BookModel
.Where(x => x.Id == 10)
.Select(x => new { x.BookName, x.Author })
.AsNoTracking()
.ToListAsync();
return View(await data);
}
catch (Exception)
{
throw;
}
}
旁注:设置 id = 10 用于测试目的。
【问题讨论】:
-
new { x.BookName, x.Author }创建一个与BookModel不同的新匿名类型。 -
@KirkLarkin 好的,很高兴知道,谢谢您的回复。你对如何修改我的代码有什么建议吗?
标签: linq asp.net-core model-view-controller linq-to-sql entity-framework-core