我们如何编写一个在* .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>
解决方法
参考
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<>来展开递归.