请参阅我的控制器并查看以下内容。我没有得到类别2的错误,但我得到类别4的错误为什么我会收到此错误?我用断点跟踪了错误。产品清单来自控制器。 foreach循环中存在问题。谢谢你的帮助。
public ActionResult Index()
{
List<Product> Products = db.Products.OrderBy(x => x.LineNumber).Where(x=>x.IsActive==true).ToList();
ViewBag.Categories = db.Categories.ToList();
return View(Products);
}
我的观点
<div class="container-index-section">
@foreach (Product item in Model.Where(x => x.Category.Name == 2))
{
<div class="container-index-category-product-@item.Size">
<div class="container-index-category-product">
<a href="~/Home/ProductDetail/@item.Id"><img src="~/ProductPhotos/Normal/@item.Photos.First().PhotoPath" alt="" style="width:65%" /></a>
<h2 style="color:orange">@item.DiscountedPrice <span style="font-size:smaller">TL</span></h2>
<p style="color:black">@Html.ActionLink(item.Name, "ProductDetail", new { id = item.Id })</p>
<a href="@Url.Action("AddToCart","Home", new { id = item.Id })" class="btn btn-default add-to-cart"><i class="fa fa-shopping-cart"></i>Sepete Ekle</a>
</div>
</div>
}
</div>
<div class="container-index-section-clear">
</div>
<div class="container-index-section">
@foreach (Product item in Model.Where(x => x.Category.Id == 4))
{
<div class="container-index-category-product-@item.Gender">
<div class="container-index-category-product">
<a href="~/Home/ProductDetail/@item.Id"><img src="~/ProductPhotos/Normal/@item.Photos.First().PhotoPath" alt="" style="width:65%" /></a>
<h2 style="color:orange">@item.DiscountedPrice <span style="font-size:smaller">TL</span></h2>
<p style="color:black">@Html.ActionLink(item.Name, "ProductDetail", new { id = item.Id })</p>
<a href="@Url.Action("AddToCart","Home", new { id = item.Id })" class="btn btn-default add-to-cart"><i class="fa fa-shopping-cart"></i>Sepete Ekle</a>
</div>
</div>
}
</div>
答案 0 :(得分:2)
您收到此错误是因为item.Photos
可能是一个空集合,而您的代码假定它至少包含一个项目。
在访问第一项之前添加if条件以检查是否存在至少一个项目将修复错误。
<a href="~/Home/ProductDetail/@item.Id">
@if(item.Photos.Any())
{
<img src="~/ProductPhotos/Normal/@item.Photos.First().PhotoPath"
alt="" style="width:65%" />
}
</a>