Recursion in ASP.NET Core Razor views

2019-06-23 15:21发布

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条回答
做个烂人
2楼-- · 2019-06-23 15:39

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.

查看更多
登录 后发表回答