将IEnumerable ViewModel传递给View

时间:2015-10-09 18:06:36

标签: c# asp.net-mvc asp.net-mvc-4 mvvm

我有两张表,Product& ProductImages

+---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; }
}

这是我的控制器

 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]'

类型的模型项

如果我在我的控制器中使用productDisplayViewModel = IEnumerable<ProductDisplayViewModel> product,我会收到错误ProductDisplayViewModel是一种类型但是像变量一样使用

修改 这是我的观点

@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>

1 个答案:

答案 0 :(得分:4)

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

假设您的视图有@model IEnumerable<ProductDisplayViewModel>

,您的控制器代码应如下所示
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 );
}