“ InvalidOperationException”错误,显示来自ASP.NET Core MVC和实体框架Core中模型的值

问题描述 投票:0回答:1

我正在尝试从控制器显示表中的值,以使用模型进行查看,但是显示错误。我已调试,并检查返回的值还可以,但是代码显示错误。我不知道问题出在哪里,请让我知道如何解决/解决此问题?

这是我的代码:

型号:

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; }
 }

RoomsController:

//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");
        }
}

RoomStatus视图:

@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-mvc asp.net-core entity-framework-core asp.net-core-3.0
1个回答
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. 控制器路线

    请确保网址,假设是

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

    RoomsController控制器处理

© www.soinside.com 2019 - 2024. All rights reserved.