ProductDisplayViewModel

ProductDisplayViewModel

我有两个表,ProductProductImages

+---PRODUCT----+
| ID           |
| Name         |
```````````````

+---PRODUCT Images----+
| ID                  |
| ProductId           |
| URL                 |
```````````````````````

我想通过Index View在两个表中的ViewModel中显示数据

这是我的ViewModel
public class ProductDisplayViewModel{
    public int ProductId { get; set; }
    public string Name {get; set;}
    public string ImageUrl { get; set; }

}

public class ProductIenumViewModel
{
    public IEnumerable<ProductDisplayViewModel> productDisplayViewModel { get; set; }
}

那是我的 Controller
 public ActionResult Index()
    {

        var product = new ProductDisplayViewModel
        {
            //ProductId = db.Products.Select(s => s.Id).ToString,
            Name = db.Products.Select(s => s.Name).ToString(),
            ImageUrl = db.ProductImages.Select(s => s.URL).ToString()
        };


        var productIenumViewModel = new ProductIenumViewModel
        {
            productDisplayViewModel =  new List<ProductDisplayViewModel> { product }
        };

        return View(productIenumViewModel);
    }

但是我得到了我已经传递了ViewModel.ProductIenumViewModel的错误,但是此字典需要'System.Collections.Generic.IEnumerable 1[ViewModel.ProductDisplayViewModel]'类型的模型项

如果我在 Controller 中使用productDisplayViewModel = IEnumerable<ProductDisplayViewModel> product,我会收到以下错误:ProductDisplayViewModel是一种类型,但像变量一样使用

编辑
这是我的 View
@model IEnumerable<MyApp.Areas.Admin.ViewModel.ProductDisplayViewModel>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table table-bordered table-striped" >
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.ImageUrl)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
            @Html.DisplayFor(modelItem => item.ImageUrl)
        </td>

        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ProductId }) |
            @Html.ActionLink("Details", "Details", new { id=item.ProductId }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ProductId })
        </td>
    </tr>
}

</table>

最佳答案

除了得到的错误之外,您还没有正确形成IEnumerable<ProductDisplayViewModel>

假设您的 View 具有@model IEnumerable<ProductDisplayViewModel>,则您的 Controller 代码应类似于以下内容

public ActionResult Index()
{

    var products = db.ProductImages
                     .Include("Product")
                     .Select(a => new ProductDisplayViewModel {
                          ProductId = a.ProductID,
                          Name = a.Product.Name,
                          ImageUrl = a.URL
                     });
    return View(products );
}

10-01 16:08