Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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?

like image 786
ygoe Avatar asked Jul 27 '16 07:07

ygoe


People also ask

What is razor view in asp net core?

Razor markup is code that interacts with HTML markup to produce a webpage that's sent to the client. In ASP.NET Core MVC, views are .cshtml files that use the C# programming language in Razor markup.

Is razor a Mvvm?

Razor Pages is sometimes described as implementing the MVVM (Model, View ViewModel) pattern. It doesn't. The MVVM pattern is applied to applications where the presentation and model share the same layer. It is popular in WPF, mobile application development, and some JavaScript libraries.

Can you mix MVC and Razor pages?

You can add support for Pages to any ASP.NET Core MVC app by simply adding a Pages folder and adding Razor Pages files to this folder. Razor Pages use the folder structure as a convention for routing requests.

What is razor in asp net?

What is Razor? Razor is a markup syntax that lets you embed server-based code (Visual Basic and C#) into web pages. Server-based code can create dynamic web content on the fly, while a web page is written to the browser.


1 Answers

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.

like image 100
Eilon Avatar answered Sep 19 '22 13:09

Eilon