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?
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.
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.
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? 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With