asp.net-core – 创建在视图中使用的方法/函数

我们如何编写一个在* .cshtml页面中使用的函数.我们曾经在视图中使用@helper或@function.我们如何做到这一点?例如,我想编写一个递归函数显示所有配置值.我怎么能这样做?

<dl>
    @foreach(var k in config.GetSubKeys())
    {
        <dt>@k.Key</dt>
        <dd>@config.Get(k.Key)</dd>
        @* Todo How can we make this a helper function/recursive? *@
        @foreach(var sk in config.GetSubKey(k.Key).GetSubKeys())
        {
            <dt>@sk.Key</dt>
            <dd>@config.Get(sk.Key)</dd>
        }
    }
</dl>

我想我们需要在project.json中添加一个依赖项,然后选择在Startup.cs中使用它.

解决方法

参考 few设计 discussions,我们只能看到在线,@ helper因设计原因被删除;更换是 View Components.

我推荐一个看起来如下的View Component:

public class ConfigurationKeysViewComponent : ViewComponent
{
    private readonly IConfiguration config;
    public ConfigurationKeysViewComponent(IConfiguration config)
    {
        this.config = config;
    }

    public IViewComponentResult Invoke(string currentSubKey = "")
    {
        return View(new ConfigurationData
        {
            Key = currentSubKey,Value = config.Get(currentSubKey),SubKeys = config.GetSubKey(currentSubKey).GetSubKeys().Select(sk => sk.Key)
        });
    }
}

您的ViewComponent的视图将相对简单:

<dt>@Model.Key</dt>
<dd>@config.Get(Model.Key)</dd>
@foreach (var sk in Model.SubKeys)
{
    @Component.Invoke("ConfigurationKeys",sk)
}

然后,您可以从根视图中调用它,如下所示:

@Component.Invoke("ConfigurationKeys")

免责声明:我在SO编辑器中写道,可能存在编译错误.此外,我不确定View Components是否支持认参数 – 您可能需要在根视图调用视图组件时添加认值“”.

或者,如果这只是调试代码,您可以使用Stack<>来展开递归.

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....