MVC:字典需要一个类型为“System.Collections.Generic.IEnumerable”1 的模型项

本文关键字:Generic Collections System IEnumerable 模型 类型 字典 一个 MVC | 更新日期: 2023-09-27 18:33:36

我收到此错误,我不确定我是否能够做到这一点,这是我的代码。

应用控制器

public ActionResult AppView()
{
    List<Application> apps;
    using (ISiteDbContext context = _resolver.GetService<ISiteDbContext>())
    {
        apps = context.Applications.ToList();
    } 
    return PartialView("AppView", apps.OrderBy(a => a.Name).ToList());
}

渲染部分 - 这位于主控制器中的视图中。

@{Html.RenderPartial("~/Views/Application/AppView.cshtml", new Example.Services.DAL.Application());} 

和我的应用程序视图

@model IEnumerable<Example.Services.DAL.Application>
@{
    ViewBag.Title = "Applications";
}
<h2>Applications</h2>
<p>
    @Html.ActionLink("Add New Application", "Create")
</p>
<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th></th>
    </tr>
    @foreach (var item in Model)
    {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
            @Html.ActionLink("Details", "Details", new { id = item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id = item.ID })
        </td>
    </tr>
    }
</table>

完整的错误消息:

传递到字典中的模型项的类型为 "example.services.DAL.Application",但此字典需要 类型的模型项 'System.Collections.Generic.IEnumerable'1[example.Services.DAL.Application]'.

MVC:字典需要一个类型为“System.Collections.Generic.IEnumerable”1 的模型项

由于错误状态,您传递了错误的类型。改变

@{Html.RenderPartial("~/Views/Application/AppView.cshtml", new Example.Services.DAL.Application());}

自:

@{Html.RenderPartial("~/Views/Application/AppView.cshtml", new List<Example.Services.DAL.Application> { new Example.Services.DAL.Application() });}

您的AppView.cshtml绑定到强类型的@model IEnumerable<Example.Services.DAL.Application>,并且在调用此视图时,您正在传递@{Html.RenderPartial("~/Views/Application/AppView.cshtml", new Example.Services.DAL.Application());}

它应该是列表对象。您必须通过Example.Services.DAL.Application() list

更改您的

@{Html.RenderPartial("~/Views/Application/AppView.cshtml", new Example.Services.DAL.Application());}

@{Html.RenderPartial("~/Views/Application/AppView.cshtml", new List<Example.Services.DAL.Application> { new Example.Services.DAL.Application() });}

您的代码正在寻找 Ienumerable,因为您传递给分部视图中的内容必须与视图中的内容相同,因此请尝试将应用程序视图的第一行更改为

@model Example.Services.DAL.Application
它对

我有用,希望它对你也有好处:D

为了对(自定义(对象的集合使用排序,您需要一种对其进行排序的方法。通常,这是通过继承"IComparable"接口来实现的。在 Object 类中,您需要一个方法 "Compare" 来确定比较对象实例以进行排序的方法(我在项目中使用"Date"(。

回顾一下:

您可以在应用程序控制器中使用它:

返回 PartView("AppView", apps.OrderBy(a => a.Name(.ToList(((;

但是为了实际排序(或在本例中为 OrderBy(,您需要在"Application"类中选择一个方法来比较列表中的实例以对它们进行排序。这是使用"比较"方法完成的:

int 比较(对象 x, 对象 y(

你如何比较完全取决于你。但是,结果是:

  • 小于零:对象 x
  • 零:对象 x = 对象 y
  • 大于零:对象 x>对象 y

我希望这有所帮助。祝你好运!

亲爱的问候,比约恩

相关文章: