【问题标题】:How to write a recursive function in a Razor View?如何在 Razor 视图中编写递归函数?
【发布时间】:2011-10-18 17:31:12
【问题描述】:

我有以下 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>();
     }
 }

我一直在关注这个帖子:

ASP.NET MVC 3 Razor recursive function

我最终得到了这段代码:

@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>

问题在于 ShowSubItems 方法不显示任何内容。模型不为空,View可以显示 @Html.DisplayFor(x =&gt; x.question, question.GetType().Name + "Print") 很好,在 ShowSubItems 方法之外。但是在 ShowSubItems 方法中没有任何东西可以渲染到视图中。怎么办?

【问题讨论】:

  • 请忘记这个问题。我忘了用@来渲染输出。

标签: asp.net-mvc-3 asp.net-mvc-2


【解决方案1】:

我认为这是因为您对 ShowSubItems 的调用是在代码块内,而不是在 render 块内。

试试这个:

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

【讨论】:

    【解决方案2】:

    试着这样称呼它:

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

    也在助手内部:

    @ShowSubItems(subitem);
    

    【讨论】:

      【解决方案3】:

      在 if 语句之前放置一个“@”标签。除非您在其中的任何位置添加 html 标记,否则这将使其中的所有内容都具有剃刀语法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-08-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多