asp.net-mvc - 在 ASP.NET Core MVC 和 Entity Framework Core 中显示模型值的“InvalidOperationException”错误
问题描述
我正在尝试从控制器显示表中的值以使用模型查看,但它显示错误。我已调试并检查值返回正常,但代码显示错误。我不知道问题出在哪里,请告诉我如何解决/修复此问题?
这是我的代码:
模型:
public class RoomsStatus
{
[Key]
public int Id { get; set; }
public DateTime CheckInDateTime { get; set; }
public DateTime CheckOutDateTime { get; set; }
public decimal DailyPricePerBed { get; set; }
public int AmountOfBeds { get; set; }
public string PriceType { get; set; }
public bool Paid { get; set; }
public string Name { get; set; }
public int RoomNumber { get; set; }
}
ApplicationDbConext:
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<RoomsStatus> RSN { get; set; }
}
房间控制器:
//view booking details and rooms status
public async Task<IActionResult> RoomsStatus(int PartnerID,int BuldingID)
{
try
{
return this.View("RoomsStatus", await _context.RSN.FromSqlRaw("EXECUTE dbo.GetRoomsStatusByID {0},{1}", PartnerID, BuldingID).ToListAsync());
}
catch (Exception e)
{
//Logger.LogError(e, "Error while displaying booking.");
return this.RedirectToAction("Error", "Base");
}
}
房间状态视图:
@model IEnumerable<FewoVerwaltung.Models.RoomsStatus>
<h1>RoomsStatus</h1>
<table class="table">
<thead>
<tr>
<th>
Name
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
</tr>
}
</tbody>
</table>
这是我得到的错误:
Stack InvalidOperationException:传递到 ViewDataDictionary 的模型项的类型为“System.Collections.Generic.List1[FewoVerwaltung.Models.RoomsStatus]”,但此 ViewDataDictionary 实例需要“FewoVerwaltung.Models.Base.BaseModel”类型的模型项
解决方案
错误是抱怨意外类型的视图模型已传递给视图。
很期待FewoVerwaltung.Models.Base.BaseModel
,
但得到了List<FewoVerwaltung.Models.RoomsStatus>
检查清单
型号类型
我看到模型类型已在视图中声明
@model IEnumerable<FewoVerwaltung.Models.RoomsStatus>
但是错误表明它没有选择声明的模型类型,所以我会尝试重新编译项目,确保它运行的是最新的项目代码。
查看文件位置
确保查看文件
RoomsStatus.cshtml
在文件夹中~/Views/Rooms/
~/Views/Rooms/RoomsStatus.cshtml
控制器路由
确保 URL,假设它是
http://localhost:{int}/Rooms/RoomsStatus?PartnerID={int}&BuldingID={int}
由
RoomsController
控制器处理
推荐阅读
- python - 如何使用 matplotlib 或 plotly 在 3-D 曲面图上叠加等高线图?
- php - Flutter Unhandled Exception: FormatException: Unexpected character (at character 4)
- sql - 如何从每一列的最大值的行中选择一个 ID?
- mongodb - 当每个字段都可搜索和可排序时,如何在 MongoDB 上正确构建索引?
- amazon-s3 - 使用目录结构在同一帐户中的两个存储桶之间同步对象
- node.js - Mocha/Chai 节点测试中的“之前”和“描述”块中的操作顺序
- android-bluetooth - 禁用按钮直到蓝牙连接
- java - 测试服务器处于生产模式
- html - 添加链接以将鼠标悬停在文本更改按钮上?
- javascript - 从 fetch API 响应中动态返回构建对象