首页 > 解决方案 > 在 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”类型的模型项

标签: asp.net-mvcasp.net-coreentity-framework-coreasp.net-core-3.0

解决方案


错误是抱怨意外类型的视图模型已传递给视图。

很期待FewoVerwaltung.Models.Base.BaseModel

但得到了List<FewoVerwaltung.Models.RoomsStatus>

检查清单

  1. 型号类型

    我看到模型类型已在视图中声明

    @model IEnumerable<FewoVerwaltung.Models.RoomsStatus>
    

    但是错误表明它没有选择声明的模型类型,所以我会尝试重新编译项目,确保它运行的是最新的项目代码。

  2. 查看文件位置

    确保查看文件RoomsStatus.cshtml在文件夹中~/Views/Rooms/

    ~/Views/Rooms/RoomsStatus.cshtml
    
  3. 控制器路由

    确保 URL,假设它是

    http://localhost:{int}/Rooms/RoomsStatus?PartnerID={int}&BuldingID={int}
    

    RoomsController控制器处理


推荐阅读