为什么我不能引用ICollection中的属性?

时间:2020-10-07 04:07:53

标签: c# asp.net asp.net-core razor-pages

我只想打印存储在Path模型的Image属性中的某些图像的路径,但是我不能,因为它是ICollection。

enter image description here

以下示例是可能的,因为它不是ICollection

@Html.DisplayFor(modelItem => item.Category.Name)

enter image description here

那是我的控制器页面

enter image description here

如您所见,我尝试了一些尝试来寻找答案

调试时,我可以看到属性,我只需要Path

enter image description here

我什至已经尝试过这样做

@Html.DisplayFor(modelItem => item.Image.Select(a => a.Path))

但是这样做,我得到了:

 InvalidOperationException: Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

运行时错误

有人可以帮助我吗?预先感谢

编辑:产品型号代码

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace WebApp.Models
{
    public class Product
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public string Description { get; set; }
        [Column(TypeName = "decimal(18,2)")]
        public decimal Price { get; set; }

        public int CategoryId { get; set; }
        public Category Category { get; set; }

        public ICollection<Image> Image { get; set; }
    }
}

2 个答案:

答案 0 :(得分:3)

您正在尝试引用ICollection<T>而不是单个字符串值。

您不能引用这样的集合,您需要遍历每个项目以获取其价值。

一种方法是这样的:

@foreach (var item in Model.Product)
{
   <tr>
        @foreach (var image in item.Image)
        {
            <td>@image.Path</td>
        }    
   </tr>
}

答案 1 :(得分:-2)

Razorview不适用于Interface和Genneric类。您可以设置List<string>新的路径