将数据从控制器传输到视图 - 列表<> / IEnumerable<>?



我正在使用实体框架构建一个asp.net MVC应用程序,但它并没有按照我希望的方式工作。

这是我的模型(不是所有的模型类,但这并不相关):

public class Product
{
    public Product()
    {
        Categories = new List<Category>();
    }
    public int ProductID { get; set; }
    public byte[] Image { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public decimal Price { get; set; }
    public Offer Offer { get; set; }
    public virtual ICollection<Category> Categories { get; set; }
}
public class Category
{
    public Category()
    {
        Products = new List<Product>();
    }
    public int CategoryID { get; set; }
    public byte[] Image { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public virtual ICollection<Product> Products { get; set; }
}

我现在正在构建一个页面,显示特定类别中的所有产品。所以,如果你去,比方说,/Category/1,它应该显示类别1中的所有产品。目前我是这样做的。在控制器中,我有这样的方法:

public ActionResult Category(int ID)
{
    return View(db.Categories.Where(c => c.CategoryID == ID).Include(c => c.Products));
}

它应该加载该特定类别的所有产品,并将数据发送到视图:

@model IEnumerable<Webshop.Models.Product>
@{
    ViewBag.Title = "Category: " + @ViewBag.CategoryName;
}
<h2>@ViewBag.CategoryName</h2>
<table>
    <tr>
        <th>@Html.DisplayNameFor(model => model.FirstOrDefault().Name)</th>
        <th>@Html.DisplayNameFor(model => model.FirstOrDefault().Price)</th>
        <th>Details</th>
    </tr>
    @foreach (var product in Model)
    {
        <tr>
            <td>@product.Name</td>
            <td>@product.Price</td>
            <td>@Html.ActionLink("Details", "Product", new { ID = product.ProductID })</td>
        </tr>
    }
</table>

这应该行得通,对吧?事实并非如此。如果我转到/Category/1,我会得到以下错误:

传递到字典中的模型项的类型为’系统。数据实体基础设施DbQuery 1[Webshop.Models.Category]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable 1[Webshop.Models.Product]'.

在控制器中添加.ToList()不起作用。

事实上,这是有道理的,但我不知道有什么其他方法可以做到这一点。更奇怪的是,我遵循了微软的asp.net教程,他们就是这么做的。

我希望任何人都能帮我解决这个问题。

您的视图期望IEnumerable<Webshop.Models.Product>的模型,但您的控制器方法返回Category对象的集合。

我会把你的观点改为:

@model Webshop.Models.Category
@{
    ViewBag.Title = "Category: " + Model.Name;
}
<h2>@ViewBag.CategoryName</h2>
<table>
    <tr>
        <th>@Html.DisplayNameFor(model => model.Products.FirstOrDefault().Name)</th>
        <th>@Html.DisplayNameFor(model => model.Products.FirstOrDefault().Price)</th>
        <th>Details</th>
    </tr>
    @foreach (var product in Model.Products)
    {
        <tr>
            <td>@product.Name</td>
            <td>@product.Price</td>
            <td>@Html.ActionLink("Details", "Product", new { ID = product.ProductID })</td>
        </tr>
    }
</table>

然后你的控制器方法变成这样:

public ActionResult Category(int ID)
{
    return View(db.Categories.Where(c => c.CategoryID == ID).Include(c => c.Products).FirstOrDefault());
}

您可能需要进行一些检查以确保找到了类别,而不是像在找不到给定的ID时那样返回空类别。

最新更新