Recursion in ASP.NET Core Razor views

2019-06-23 15:12发布

问题:

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. Not sure whether such nice inline HTML code with tag helpers would still be allowed there, it didn't seem so. Another option is HTML helpers in a .cs file, no inline HTML here for sure. @helper doesn't seem to be available anymore.

What other options do I have to define a function and keep the inline HTML syntax that Razor offers?

回答1:

Put the code for rendering a comment inside a partial view, and render it with a call to @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.