我可以在HtmlHelper中注册Orchard资源吗?

时间:2017-05-22 10:19:49

标签: orchardcms

我知道这违反了MVC原则和最佳做法。

我有一大堆自定义Angular组件,每个组件都需要一大堆可选参数,每个组件都需要不同的远程样式表和javascript文件。我想用HtmlHelper渲染它们,而不必在我使用它的任何地方手动包含正确的资源。

我希望这可以做到这一点,但它并没有

public static class HtmlExtensions
{
    private static IResourceManager _resourceManager;

    // Executed in the Activated method of an OrchardShellEvents implementation
    public static void SetResourceManager(IResourceManager resourceManager)
    {
        _resourceManager = resourceManager;
    }

    public static MvcHtmlString Angular(this HtmlHelper helper, CustomAngularComponent component)
    {
        // Require the resources
        var _styleRegister = new ResourceRegister(helper.ViewDataContainer, _resourceManager, "Style");
        var _scriptRegister = new ResourceRegister(helper.ViewDataContainer, _resourceManager, "Script");

        _styleRegister.Require(component.StyleSheet).AtHead();

        if (!string.IsNullOrEmpty(component.Script))
        {
            _scriptRegister.Require(component.Script).AtFoot();
        }

        // Create tag
        var tag = new TagBuilder(component.Tag);
        tag.MergeAttributes(component.Parameters);

        return new MvcHtmlString(tag.ToString(TagRenderMode.SelfClosing));
    }
}

我可以使用任意Shape作为助手,例如:

@Display(New.Angular(Model: new CustomAngularComponent(...)))

但是具有强类型参数的助手会感觉好多了。

1 个答案:

答案 0 :(得分:0)

This comment关于另一个果园问题让我失望了。事实证明,只需注入public static class HtmlExtensions { private static Work<IResourceManager> _resourceManager; // Executed in the Activated method of an OrchardShellEvents implementation public static void SetResourceManager(Work<IResourceManager> resourceManager) { _resourceManager = resourceManager; } public static MvcHtmlString Angular(this HtmlHelper helper, CustomAngularComponent component) { // Require the resources _resourceManager.Value.Require("stylesheet", component.StyleSheet).AtHead(); if (!string.IsNullOrEmpty(component.Script)) { _resourceManager.Value.Require("script", component.Script).AtFoot(); } // Create tag var tag = new TagBuilder(component.Tag); tag.MergeAttributes(component.Parameters); return new MvcHtmlString(tag.ToString(TagRenderMode.SelfClosing)); } } 并直接使用它就足以使我的设置工作。请注意,这不符合最佳MVC实践,通过这样做,我牺牲了可维护性以支持可读性。

{{1}}