【问题标题】:Access all available ViewComponents as a list以列表形式访问所有可用的 ViewComponent
【发布时间】:2017-03-16 21:01:34
【问题描述】:

我想在 asp.net 核心 MVC (mvc6?) 项目中搜索所有可用 ViewComponents 的列表,类似这样。

ViewComponent 的 Default.cshtml

 foreach (var section in Model.sections)
{
    var sectionId = section.Id;
    if (_siteSettings.AvailableComponents.Any(c => c == sectionId))
    {
        @await Component.InvokeAsync(sectionId);
    }
    else
    {
        <p>Could not find component: @sectionId </p>            
    }        
}

现在,我已经设法通过在运行时可用的列表中手动注册每个组件来做到这一点。但是我想要完成的是在每个组件类文件中简单地注册每个视图组件,如下所示:

public class NewsList : ViewComponent
{

    private ISiteSettings _siteSettings;
    private string ComponentName = "NewsList";

    public NewsList(ISiteSettings siteSettings)
    {
        _siteSettings = siteSettings;

        _siteSettings.AvailableComponents.Add(ComponentName);
    }


    public async Task<IViewComponentResult> InvokeAsync()
    {            
        return View();
    }
}

问题是每个视图组件的构造函数在视图组件被渲染之前不会被执行,我需要以某种方式“自动”注册所有组件。这可能吗?

【问题讨论】:

  • 不知道是否有任何方法可以列出所有子类 ViewComponent 的类(前提是您通过从项目中的 ViewComponent 继承来创建视图组件)。可以在中间件级别获得这些视图组件的列表吗?

标签: c# asp.net-mvc asp.net-core-mvc


【解决方案1】:

为此,您需要使用反射。使用Assembly,可以获取项目中的所有Types,然后过滤BaseTypetypeof(ViewComponent)的位置。

var listOfViewComponents = Assembly
                            .GetEntryAssembly()
                            .GetTypes()
                            .Where(x => x.GetTypeInfo().BaseType == typeof(ViewComponent));

希望这会有所帮助。

【讨论】:

  • 美丽,像魅力一样!我有反思,但我认为 ViewComponents 可能有一些内置方式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-10
  • 2014-05-27
  • 2015-08-25
  • 2021-11-23
  • 1970-01-01
相关资源
最近更新 更多