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?

5
  • you can check if item has sublist and then just render the same view again. Commented Jul 27, 2016 at 8:01
  • i have implemented it in ASP.NET 4.6 and i don't have any idea about the client side syntax of core. If you want i will still share the code Commented Jul 27, 2016 at 8:06
  • My scenario was that if the comment has a reply, then render the comments view again for the replies to that comment, but you need to have a bool field to see if that item has subitems for that code to work Commented Jul 27, 2016 at 8:10
  • This whole code is within a complete view that renders a result from an action. I don't understand how this should be "rendered again". Commented Jul 27, 2016 at 8:25
  • I have used @Html.RenderAction() method to render the same action again. Commented Jul 27, 2016 at 8:50

1 Answer 1

25

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This is the only solution that seems to work with .NET Core 2.x (and 1.x?). If you're fortunate enough to be on .NET Core 3.x (and presumably .NET Framework 5) you can just use a local void method and have that call itself.
It seems a bit excessive to need an entirely separate .cshtml file for a few lines of repeated HTML...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.