[英]Recursion in ASP.NET Core Razor views
I have the following code right now to write a flat list of items with a link to a controller action: 我现在有以下代码来编写一个包含控制器操作链接的项目的平面列表:
<ul>
@foreach (var item in items)
{
<li>
<a asp-controller="Home" asp-action="Demo" asp-route-itemName="@item.Name">
@item.Name
</a>
</li>
}
</ul>
Now this must become recursive. 现在这必须变为递归。 Items can also contain subitems.
项目还可以包含子项目。 For recursion I need some sort of function.
对于递归,我需要某种功能。 I know I could use
@functions
and define the function in the .cshtml file. 我知道我可以使用
@functions
并在.cshtml文件中定义该函数。 Not sure whether such nice inline HTML code with tag helpers would still be allowed there, it didn't seem so. 不确定是否仍然允许带有标记助手的这种漂亮的内联HTML代码,它似乎不是这样。 Another option is HTML helpers in a .cs file, no inline HTML here for sure.
另一个选项是.cs文件中的HTML帮助程序,这里没有内联HTML。
@helper
doesn't seem to be available anymore. @helper
似乎不再可用了。
What other options do I have to define a function and keep the inline HTML syntax that Razor offers? 我还有哪些其他选项来定义函数并保留Razor提供的内联HTML语法?
Put the code for rendering a comment inside a partial view, and render it with a call to @Html.Partial("comment", comment)
. 将用于呈现注释的代码放在局部视图中,并通过调用
@Html.Partial("comment", comment)
来呈现它。
Then within that comment partial view you'd have something like 然后在那个评论局部视图中你会有类似的东西
@model Comment
Title: @Model.Title
Message: @Model.Message
@if (Model.ChildComments.Any())
{
<ul>
@foreach (var childComment in Model.ChildComments)
{
<li>
@Html.Partial("comment", childComment)
</li>
}
</ul>
}
This will render each comment, plus all its children (if any), recursively. 这将递归地呈现每个注释及其所有子项(如果有)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.