C# Asp Mvc问题模型项已传递

C# Asp Mvc问题模型项已传递,c#,model-view-controller,C#,Model View Controller,这是我的控制器代码: public ActionResult ShowProducts(string productName) { ProductRepository blProduct = new ProductRepository(); var src = blProduct.Where(p => p.Url.Trim() == productName.Trim()); if (src.Any()) {

这是我的控制器代码:

 public ActionResult ShowProducts(string productName)
    {

        ProductRepository blProduct = new ProductRepository();
        var src = blProduct.Where(p => p.Url.Trim() == productName.Trim());
        if (src.Any())
        {
            return View(src.Single());
        }
        else
        {
            return RedirectToAction("Index");
        }

    }
这就是我的查看页面代码:

@model IEnumerable<GymInternetShop.Models.DomainModels.Product>

如果要显示所有产品,为什么只传递src.Single()

您的视图也需要一个IEnumerable,但只需要一个

我要换衣服

var src = blProduct.Where(p => p.Url.Trim() == productName.Trim());


不过要小心,您可能会在
src
中返回
IQueryable
。使用
ToList()
确保它返回
IEnumerable
。这是正确的。我不能确定,因为我们还没有看到存储库,但我会添加它以防万一。谢谢非常感谢你,兄弟!这就是工作!如果要迭代
IEnumerable
,为什么要使用
Single
?只需在
Where
之后使用
ToList()
,您将从模型中获得
IEnumerable
集合。Try return视图(src.Select(s=>s).First()可能重复。您返回的不是IEnumerable,而是EF的动态代理。如果要返回IEnumerable的列表,请阅读此处
The model item passed into the dictionary is of type 'System.Data.Entity.DynamicProxies.Product_9F73B4E1D7A93B6E9A923F87D780EE891805309BEF7B2609BEB9BC3DE1B25A33', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[GymInternetShop.Models.DomainModels.Product]'.
var src = blProduct.Where(p => p.Url.Trim() == productName.Trim());
List<Product> src = blProduct.Where(p => p.Url.Trim() == productName.Trim()).ToList();
if (src.Any())
        {
            return View(src);
        }