将 List 转换为 IEnumerable 时出错

Error when converting List to IEnumerable

我正在尝试显示模型的默认索引页。但是我收到以下错误。

The model item passed into the dictionary is of type 'System.Collections.Generic.List 1[System.Boolean]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[EDIWebsite.Models.Error_Details]'.

控制器

 public ActionResult FindRelatedBols(string bolnumber)
        {
            if (bolnumber == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var error_Summaries = db.Error_Details.Select(r => r.BOL == bolnumber);
            if (error_Summaries == null)
            {
                return HttpNotFound();
            }
            return PartialView("~/Views/Error_Details/Index.cshtml",error_Summaries.ToList());
        }

查看

@model IEnumerable<EDIWebsite.Models.Error_Details>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Source_System)
        </th>
.
.
.
            @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
        </td>
    </tr>
}

</table>

错误不言自明。您的视图被强类型化为 Error_Details objects.Your 的集合当前代码正在生成 IQueryable<bool> 作为 error_Summaries 变量的类型,您稍后将调用 ToList()那,这将生成一个布尔值列表(List<bool>)。

您的视图正在期待某些东西(IEnumerable<Error_Details>)而您的操作方法正在传递其他东西(List<bool>),因此出现类型不匹配异常!

您需要将 Error_Details 个对象的集合传递给视图。我假设您想传递一个过滤后的项目列表,该列表与您的 bolnumber 参数具有相同的 BOL 值。您可以使用 LINQ Where 方法进行过滤。

var items =  db.Error_Details.Where(a=>a.BOL == bolnumber).ToList();
return PartialView("~/Views/Error_Details/Index.cshtml",items);

假设 Error_Details class 上的 BOL 属性 是 string 类型。