以列表形式访问所有可用的ViewComponents

时间:2017-03-16 12:19:30

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

我想在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之前都不会被执行,我需要注册所有组件&#34;自动&#34;不知何故。这可能吗?

1 个答案:

答案 0 :(得分:1)

为此,您需要使用反射。使用protected function driver() { $capabilities = new DesiredCapabilities([ WebDriverCapabilityType::BROWSER_NAME => WebDriverBrowserType::CHROME, WebDriverCapabilityType::PLATFORM => WebDriverPlatform::ANY, WebDriverCapabilityType::PROXY => [ 'proxyType' => 'manual', 'httpProxy' => 'http://proxy:8080', // have also tried without specifying http:// 'sslProxy' => 'http://proxy:8080', // have also tried without specifying http:// ], ]); return RemoteWebDriver::create( 'http://localhost:9515', $capabilities, null, null, $http_proxy = 'http://proxy', // have also tried without specifying http:// $http_proxy_port = '8080', null ); } ,您可以获取项目中的所有类型,然后过滤AssemblyBaseType的位置。

typeof(ViewComponent)

希望这有帮助。