I have a MVC application which has a Controller that has a recursive method which returns an IEnumerable
public static IEnumerable<Category> GetSubCategoriesFor(int catId)
{
var subs = _db.Category.Where(c => c.parrent_id == catId);
foreach (var sub in subs)
{
yield return sub;
// Recursive call
foreach (var subsub in GetSubCategoriesFor(sub.category_id))
{
yield return subsub;
}
}
The point is i need my view to show all Categories, subcategories and Questions in subcategories (It’s a questionnarie)
So my question is, how can i call this method from my View??
I have seen some examples where they use Html.Action but i cannot iterate over a string or void
Thanks in advance!
This
GetSubCategoriesFormethod seems to be flattening your hierarchical structure by returning a list which is mixing categories, subcategories, …Personally I would use display templates. For example if I have the following view model:
I would populate it in the controller. In my example I have hardcoded the values for demonstration purposes but in your real example those values would obviously come from a database or something and they will be retrieved through a repository:
and then my
~/Views/Home/Index.aspxview will look like this:and then I would define a display template for a category (
~/Views/Home/DisplayTemplates/CategoryViewModel.ascx):Now it is the ASP.NET MVC templated helpers that will take care of looping through the tree structure of categories and show the contents on the view. You could extend this further by defining a complex
QuestionViewModelinstead of the string I’ve used and by defining a display template for this question~/Views/Home/DisplayTemplates/QuestionViewModel.ascxit will be rendered for each element of theQuestionsproperty of a category.