Search code examples
c#asp.netasp.net-mvcrazorepiserver

Getting error foreach statement cannot operate on variables of type 'xyz' because 'xyz' does not contain a public definition for 'GetEnumerator'


I have created a Model based on an 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();
        }
    }
}

And I am trying to create a shared view for it:

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

Unfortunatley I don't understand what I am doing wrong.


Solution

  • Here, you are attempting to iterate over Model:

    foreach (var linkItem in Model)
    

    However, Model is of type CustomTopNavigationItemtBlock, which cannot be iterated using foreach, as it does not implement IEnumerable.

    It seems that you are trying to loop over the CustomTopNavigationLinks property, which can be done like this:

    foreach (var linkItem in Model.CustomTopNavigationLinks)