【问题标题】:Getting error foreach statement cannot operate on variables of type 'xyz' because 'xyz' does not contain a public definition for 'GetEnumerator'获取错误 foreach 语句无法对“xyz”类型的变量进行操作,因为“xyz”不包含“GetEnumerator”的公共定义
【发布时间】:2021-09-16 23:07:10
【问题描述】:

我创建了一个基于 EpiServer LinkItemCollection 的模型:

namespace ProjectX.Site.Models.Blocks
{
    [SiteContentType(
        GUID = "b9978bf2-f3da-4164-8fa2-3694c2ce0377", 
        AvailableInEditMode = false)]
    [SiteImageUrl]
    public class CustomTopNavigationItemtBlock : SiteBlockData
    {

        [CultureSpecific]
        [MinItemCount(0)]
        [MaxItemCount(2)]
        [Display(Order = 10)]
        public virtual LinkItemCollection CustomTopNavigationLinks { get; set; }

        public override int WordCount
        {
            get => throw new System.NotImplementedException();
            set => throw new System.NotImplementedException();
        }
    }
}

我正在尝试为它创建一个共享视图:

@model CustomTopNavigationItemtBlock

@if (Model != null)
{
    @foreach (var linkItem in Model)
    {
        <li>
            <a class=""
               href="@Url.PageUrl(linkItem.Href)"
               target="@linkItem.Target"
               title="@linkItem.Title"
               tabindex="1"
               data-toggle=""
               role="button">
                @linkItem.Text
            </a>
        </li>
    }
}

不幸的是,我不明白我做错了什么。

【问题讨论】:

  • foreach (var linkItem in Model.CustomTopNavigationLinks)
  • CustomTopNavigationItemtBlock 未实现 IEnumerable 因此出现错误。您的预期行为是什么?
  • Jonathan Barclays 的建议奏效了。但我不明白为什么?
  • @BrokenCode 因为ModelCustomTopNavigationItemtBlock。它不是一个集合,因此不能迭代。但是,它确实有一个 CustomTopNavigationLinks 类型的 LinkItemCollection 属性,这就是您要迭代的内容。
  • 啊,非常感谢,我现在明白了!请随时提供此作为答案,以便我给您点赞。

标签: c# asp.net asp.net-mvc razor episerver


【解决方案1】:

在这里,您正在尝试迭代 Model

foreach (var linkItem in Model)

但是,Model 属于 CustomTopNavigationItemtBlock 类型,不能使用 foreach 进行迭代,因为它没有实现 IEnumerable

您似乎正在尝试遍历 CustomTopNavigationLinks 属性,可以这样做:

foreach (var linkItem in Model.CustomTopNavigationLinks)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-21
    • 2017-03-08
    • 2016-03-27
    • 1970-01-01
    相关资源
    最近更新 更多