ASP.NET Core Razor视图中的递归

编程入门 行业动态 更新时间:2024-10-27 00:22:33
本文介绍了ASP.NET Core Razor视图中的递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我现在有以下代码来编写一个平面项目列表,并带有指向控制器动作的链接:

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>

现在,这必须变得递归.项目还可以包含子项目.对于递归,我需要某种功能.我知道我可以使用@functions并在.cshtml文件中定义函数.不确定是否仍允许在此处使用带有标签帮助程序的漂亮的内联HTML代码,但事实并非如此.另一个选项是.cs文件中的HTML帮助器,这里肯定没有内联HTML. @helper似乎不再可用.

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.

我还必须定义什么其他功能并保留Razor提供的内联HTML语法?

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

推荐答案

将用于渲染注释的代码放入局部视图中,并通过调用@Html.Partial("comment", comment)进行渲染.

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.

更多推荐

ASP.NET Core Razor视图中的递归

本文发布于:2023-11-24 19:01:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1626445.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   视图   NET   ASP   Razor

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!