Andre Silveira

Andre Silveira

  • 1.2k
  • 148
  • 13.4k

Proper way to get a collection on the view

Aug 9 2021 7:38 PM

Hi all,

I have a class "Category" with a List<SubCategory> with the primary key mapped.

How do I list the category and subcategory?

The code bellow is not listing the subcategorys

@model IList<Receita.Models.Category>
    <div class="col-md-12" style="padding-top:50px;">
        <ul>
            @foreach (var Item in Model)
            {
            <li>
                @Item.CategoriaNome
                @if (!(Item.SubCategorias == null))
                {
                    <ul>
                        @foreach (var subcategoria in Item.SubCategorias)
                        {
                            <li>@subcategoria.Nome</li>
                        }
                    </ul>
                }
            </li>
            }
        </ul>
    </div>

The classes

Category

    public class Category
    {
        [Key]
        public int Id { get; set; }
        [Required(ErrorMessage = "Nome obrigatório")]
        [Display(Name = "Nome da categoria")]
        public string CategoriaNome { get; set; }
        [Display(Name = "Idioma:")]
        public string Idioma { get; set; }
        public List<SubCategory> SubCategorias { get; set; }
        public List<TheThing> Things{ get; set; }
    }

SubCategory

    public class SubCategory
    {
        [Key]
        public int Id { get; set; }
        public string Nome { get; set; }
        public string Idioma { get; set; }
        public int CategoriaId { get; set; }
        [ForeignKey("CategoriaId")]
        public Category Categoria { get; set; }
        public List<theThing> Things{ get; set; }
    }

Thanks in advance


Answers (2)