0

So I have built a recursive function that generates a collection of Category objects.

[ChildActionOnly]
public ActionResult FindAllCategorias()
{
    var categoriasDb = _categoriaRepository.FindAllCategorias().Where(s => s.CategoriaPadreId == null);
    List<CategoriaModel> model = new List<CategoriaModel>();

    foreach (var categoria in categoriasDb)
    {
            model.Add(new CategoriaModel()
                            {
                                CategoriaId = categoria.CategoriaId,
                                Nombre = categoria.Nombre,
                                Encabezado = categoria.Encabezado
                            });
    }

    foreach (var categoriaModel in model)
    {
        categoriaModel.Subcategorias = FindSubcategoriesForCategory(categoriaModel.CategoriaId);
    }

    return PartialView(model);
}

private List<CategoriaModel> FindSubcategoriesForCategory(int id)
{
    var subcategorias = _categoriaRepository.FindAllCategorias().Where(c => c.CategoriaPadreId == id);

    List<CategoriaModel> subcategoriasModel = new List<CategoriaModel>();

    foreach (var subcategoria in subcategorias)
    {
        subcategoriasModel.Add(new CategoriaModel()
                                    {
                                        CategoriaId = subcategoria.CategoriaId,
                                        Nombre = subcategoria.Nombre,
                                        Encabezado = subcategoria.Encabezado,
                                        Subcategorias = FindSubcategoriesForCategory(subcategoria.CategoriaId)
                                    });
    }

    return subcategoriasModel;
}

Now in my View, how do you suggestion I use recursion to spit out each Category in a template I choose? I'm not sure how to something like this in a View.

Only Bolivian Here
  • 35,719
  • 63
  • 161
  • 257

2 Answers2

1

You could use a recursive display template:

@model List<CategoriaModel>
<ul>
    @Html.DisplayForModel()
</ul>

and then define a custom display template for a category (~/Views/Shared/DisplayTemplates/CategoriaModel.cshtml):

@model CategoriaModel
<li>
    @Html.DisplayFor(x => x.Encabezado) ... and something else about the category  
    <ul>
       @Html.DisplayFor(x => x.Subcategorias)
    </ul>
</li>

You may also find the following post useful in terms of optimizing your code and data access.

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thanks. :) One more bit, I'm not a SQL guy, I know just enough to get by on. How large is the performance difference between using my recursive foreign key schema and using a nested set like in the link you suggested? Thanks! – Only Bolivian Here Jan 20 '12 at 17:03
-1

You could try building your output directly using MvcHtmlString.Create() within your methods or you can create a helper to access your methods in the ui using razor.

Vinny Marquez
  • 547
  • 3
  • 12