所以我构建了一个递归函数,生成Category
个对象的集合。
[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;
}
现在在我的视图中,您如何建议我使用递归来吐出我选择的模板中的每个类别?我不确定在视图中如何做到这一点。
答案 0 :(得分:1)
您可以使用递归显示模板:
@model List<CategoriaModel>
<ul>
@Html.DisplayForModel()
</ul>
然后为类别(~/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>
您可能还会发现following post在优化代码和数据访问方面非常有用。
答案 1 :(得分:-1)
您可以尝试使用方法中的MvcHtmlString.Create()直接构建输出,也可以使用razor创建一个帮助来访问ui中的方法。