加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 09:55:08 所属栏目:asp.Net 来源:网络整理
导读:我们如何编写一个在* .cshtml页面中使用的函数.我们曾经在视图中使用@helper或@function.我们如何做到这一点?例如,我想编写一个递归函数来显示所有配置值.我怎么能这样做? dl @foreach(var k in config.GetSubKeys()) { dt@k.Key/dt dd@config.Get(k.Key)/
我们如何编写一个在* .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<>来展开递归.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读