2

I have the following ViewModel:

 public class AllQuestionsInCategoriesViewModel
 {
     public string Category_Name { get; set; }
     public string Category_Number { get; set; }
     public List<ShowQuestionViewModel> questions { get; set; }
     public List<AllQuestionsInCategoriesViewModel> SubCategories { get; set; }

     public AllQuestionsInCategoriesViewModel()
     {
         questions = new List<ShowQuestionViewModel>();
         SubCategories = new List<AllQuestionsInCategoriesViewModel>();
     }
 }

I've been following this thread:

ASP.NET MVC 3 Razor recursive function

And i ended up with this code:

@model List<MvcApplication3.Models.ViewModels.Category.AllQuestionsInCategoriesViewModel>

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title>PrintSchema</title>
    <link type="text/css" href="../../Content/Print.css" rel="Stylesheet" />
</head>
<body>

@{
    foreach(var cq in Model) {
        ShowSubItems(cq);
    }
}

@helper ShowSubItems(MvcApplication3.Models.ViewModels.Category.AllQuestionsInCategoriesViewModel MyObj)
{

    <h1>@MyObj.Category_Number  @MyObj.Category_Name</h1>
    foreach (var question in MyObj.questions)
    {
        @Html.DisplayFor(x => question, question.GetType().Name + "Print")
    }

    if (MyObj.SubCategories.Count != null || MyObj.SubCategories.Count != 0)
    {
        foreach(var subitem in MyObj.SubCategories)
        {
            ShowSubItems(subitem);
        }          
    }
}

</body>
</html>

The problem is that the ShowSubItems method doesnt Display anything. The model is not empty, and the View can display @Html.DisplayFor(x => x.question, question.GetType().Name + "Print") just fine, outside of the ShowSubItems method. But nothing gets rendere to the View in the ShowSubItems method. Howcome?

Community
  • 1
  • 1
Kenci
  • 4,794
  • 15
  • 64
  • 108

3 Answers3

3

I think it's because your call to ShowSubItems is inside a code block and not in a render block.

Try this:

@{
    foreach(var cq in Model) {
        @ShowSubItems(cq)
    }
}
Charlino
  • 15,802
  • 3
  • 58
  • 74
1

Try calling it like this:

@foreach(var cq in Model) {
    @ShowSubItems(cq);
}

Also inside the helper:

@ShowSubItems(subitem);
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

put a '@' tag before the if statement. That will make everything inside it razor syntax unless you add a html tag anywhere inside it.