Ejemplo n.º 1
0
        public async Task <IViewComponentResult> InvokeAsync()
        {
            var controllerName = Convert.ToString(ViewContext.RouteData.Values["controller"]);
            var actionName     = Convert.ToString(ViewContext.RouteData.Values["action"]);
            var areaName       = Convert.ToString(ViewContext.RouteData.Values["area"]);
            var currentMenu    = await _menuService.SingleAsync(areaName, controllerName, actionName);

            CurrentNavMenu = currentMenu == null || currentMenu.IsNav
                ? currentMenu
                : await _menuService.SingleAsync(a => a.ID == currentMenu.ParentID);

            var userId = new Guid(HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value);

            AccessMenu = await _menuService.QueryMenuViewModel(userId);


            var applicationList = await _applicationService.QueryAsync(a => true);

            var html = new DefaultTagHelperContent();

            foreach (var application in applicationList)
            {
                var tag = new TagBuilder("li");
                tag.MergeAttribute("class", "heading");
                var tagH3 = new TagBuilder("h3");
                tagH3.MergeAttribute("class", "uppercase");
                tagH3.InnerHtml.AppendHtml(application.Name);
                tag.InnerHtml.AppendHtml(tagH3);
                html.AppendHtml(tag);
                var appMenus = AccessMenu.Where(a => a.ApplicationID == application.ID && a.IsNav);

                foreach (var item in appMenus.Where(a => a.ParentID == default(Guid)))
                {
                    html.AppendHtml(CreateMenuTag(appMenus, item));
                }
            }

            return(View("_LayoutSidebar", html));
        }
    public void SetHtmlContent_ClearsExistingContent()
    {
        // Arrange
        var tagHelperContent = new DefaultTagHelperContent();

        tagHelperContent.AppendHtml("Contoso");

        // Act
        tagHelperContent.SetHtmlContent("Hello World!");

        // Assert
        Assert.Equal("Hello World!", tagHelperContent.GetContent(new HtmlTestEncoder()));
    }
        public async Task ProcessAsync_CheckedNullAndModelValueDoesEqualsValueDoesNotSetCheckedAttribute()
        {
            // Arrange
            var modelExplorer = new EmptyModelMetadataProvider().GetModelExplorerForType(typeof(Model), "Foo");
            var viewContext   = new ViewContext();

            var radiosContext = new CheckboxesContext(
                idPrefix: "prefix",
                resolvedName: "mycheckboxes",
                viewContext: viewContext,
                aspFor: new ModelExpression("Foo", modelExplorer));

            var context = new TagHelperContext(
                tagName: "govuk-checkboxes-item",
                allAttributes: new TagHelperAttributeList(),
                items: new Dictionary <object, object>()
            {
                { typeof(CheckboxesContext), radiosContext }
            },
                uniqueId: "test");

            var output = new TagHelperOutput(
                "govuk-checkboxes-item",
                attributes: new TagHelperAttributeList(),
                getChildContentAsync: (useCachedResult, encoder) =>
            {
                var tagHelperContent = new DefaultTagHelperContent();
                tagHelperContent.AppendHtml(new HtmlString("Label"));
                return(Task.FromResult <TagHelperContent>(tagHelperContent));
            });

            var htmlGenerator = new Mock <DefaultGovUkHtmlGenerator>()
            {
                CallBase = true
            };

            htmlGenerator
            .Setup(mock => mock.GetModelValue(viewContext, modelExplorer, "Foo"))
            .Returns("bar");

            var tagHelper = new CheckboxesItemTagHelper(htmlGenerator.Object)
            {
                Value = "baz"
            };

            // Act
            await tagHelper.ProcessAsync(context, output);

            // Assert
            Assert.False(radiosContext.Items.Single().IsChecked);
        }
    public void IsEmptyOrWhiteSpace_FalseAfterAppendTagHelperContent()
    {
        // Arrange
        var tagHelperContent       = new DefaultTagHelperContent();
        var copiedTagHelperContent = new DefaultTagHelperContent();

        copiedTagHelperContent.SetContent("Hello");

        // Act
        tagHelperContent.AppendHtml(copiedTagHelperContent);

        // Assert
        Assert.False(tagHelperContent.IsEmptyOrWhiteSpace);
    }
    public void IsEmptyOrWhiteSpace_TrueAfterAppendTagHelperContent_WithDataToEncode(string data)
    {
        // Arrange
        var tagHelperContent       = new DefaultTagHelperContent();
        var copiedTagHelperContent = new DefaultTagHelperContent();

        copiedTagHelperContent.Append(data);

        // Act
        tagHelperContent.AppendHtml(copiedTagHelperContent);

        // Assert
        Assert.True(tagHelperContent.IsEmptyOrWhiteSpace);
    }
Ejemplo n.º 6
0
        /// <summary>
        /// Merges multiple TagHelperContents into a single one
        /// </summary>
        public static TagHelperContent ToSingleTagHelperContent(this IEnumerable <TagHelperContent> contents)
        {
            if (contents == null)
            {
                throw new ArgumentNullException(nameof(contents));
            }
            var content = new DefaultTagHelperContent();

            foreach (var tagHelperContent in contents)
            {
                content.AppendHtml(tagHelperContent);
            }
            return(content);
        }
Ejemplo n.º 7
0
        public void TestLazy()
        {
            var attributes = new TagHelperAttributeList {
                { UiConst.Lazy, true }
            };
            TagHelperContent content = new DefaultTagHelperContent();

            content.AppendHtml("a");
            var result = new String();

            result.Append("<nz-tab>");
            result.Append("<ng-template nz-tab=\"\">a</ng-template>");
            result.Append("</nz-tab>");
            Assert.Equal(result.ToString(), GetResult(attributes, content: content));
        }
        public void TestContent()
        {
            var result = new String();

            result.Append("<td>");
            result.Append("content");
            result.Append("</td>");

            var content = new DefaultTagHelperContent();

            content.AppendHtml("content");
            _builder = new TextColumnBuilder("a", null, content);
            _builder.Init();
            Assert.Equal(result.ToString(), _builder.ToString());
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Converts a <see cref="TagHelperOutput" /> to a <see cref="TagHelperContent" />
        /// </summary>
        public static TagHelperContent ToTagHelperContent(this TagHelperOutput output)
        {
            var content = new DefaultTagHelperContent();

            // Set PreElement
            content.AppendHtml(output.PreElement);

            // Copy Element (Tag and Attributes).
            // "contentBuilder" is either "destination" or "TagBuilder.InnerHtml".
            CopyElement(output, content, out var contentBuilder);

            // Set Content
            if (contentBuilder != null)
            {
                contentBuilder.AppendHtml(output.PreContent);
                contentBuilder.AppendHtml(output.Content);
                contentBuilder.AppendHtml(output.PostContent);
            }

            // Set PostElement
            content.AppendHtml(output.PostElement);

            return(content);
        }
    public void AppendHtml_DoesNotGetEncoded()
    {
        // Arrange
        var tagHelperContent = new DefaultTagHelperContent();

        tagHelperContent.AppendHtml("Hi");

        var writer = new StringWriter();

        // Act
        tagHelperContent.WriteTo(writer, new HtmlTestEncoder());

        // Assert
        Assert.Equal("Hi", writer.ToString());
    }
Ejemplo n.º 11
0
        /// <summary>
        ///     Generate the html content for a series of pager items.
        /// </summary>
        /// <param name="items">The collection of <see cref="PagerRenderingItem" /> to generate the content.</param>
        /// <returns>The final <see cref="IHtmlContent" />.</returns>
        protected static IHtmlContent GeneratePagerItems(IEnumerable <PagerRenderingItem> items)
        {
            if (items == null)
            {
                throw new ArgumentNullException(nameof(items));
            }

            var content = new DefaultTagHelperContent();

            foreach (var i in items)
            {
                content.AppendHtml(GeneratePagerItem(i));
            }

            return(content);
        }
Ejemplo n.º 12
0
        public async Task ProcessAsync_ComputesCorrectIdForSubsequentItemsWhenNotSpecified()
        {
            // Arrange
            var checkboxesContext = new CheckboxesContext(
                idPrefix: "prefix",
                resolvedName: "mycheckboxes",
                aspFor: null,
                viewContext: null);

            checkboxesContext.AddItem(new CheckboxesItem()
            {
                Content = new HtmlString("First")
            });

            var context = new TagHelperContext(
                tagName: "govuk-checkboxes-item",
                allAttributes: new TagHelperAttributeList(),
                items: new Dictionary <object, object>()
            {
                { typeof(CheckboxesContext), checkboxesContext }
            },
                uniqueId: "test");

            var output = new TagHelperOutput(
                "govuk-checkboxes-item",
                attributes: new TagHelperAttributeList(),
                getChildContentAsync: (useCachedResult, encoder) =>
            {
                var tagHelperContent = new DefaultTagHelperContent();
                tagHelperContent.AppendHtml(new HtmlString("Label"));
                return(Task.FromResult <TagHelperContent>(tagHelperContent));
            });

            var tagHelper = new CheckboxesItemTagHelper(new DefaultModelHelper())
            {
                IsChecked = true,
                Value     = "V"
            };

            // Act
            await tagHelper.ProcessAsync(context, output);

            // Assert
            Assert.Equal("prefix-1", checkboxesContext.Items.Last().Id);
            Assert.Equal("prefix-1-item-hint", checkboxesContext.Items.Last().HintId);
            Assert.Equal("conditional-prefix-1", checkboxesContext.Items.Last().ConditionalId);
        }
        /// <summary>
        ///     Generate the a series of alert dialogs for a collection of <see cref="OperationMessage" /> items.
        /// </summary>
        /// <param name="messages">The collection of all <see cref="OperationMessage" /> items.</param>
        /// <param name="listStyle">The list style of the <see cref="OperationMessage" />.</param>
        /// <param name="useTwoLineMode">If the two line mode should be used.</param>
        /// <returns>The generated HTML content which represent as a series of alert dialogs.</returns>
        private IHtmlContent GenerateAlertList(IEnumerable <OperationMessage> messages, MessageListStyle listStyle,
                                               bool useTwoLineMode)
        {
            var tag = new TagBuilder("div");

            var content = new DefaultTagHelperContent();

            foreach (var message in messages)
            {
                content.AppendHtml(GenerateAlertItem(message, listStyle == MessageListStyle.AlertDialogClosable,
                                                     useTwoLineMode));
            }

            tag.InnerHtml.AppendHtml(content);

            return(tag);
        }
        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            var childContent = await output.GetChildContentAsync();

            var modalContext = (ModalContext)context.Items[typeof(ModalTagHelper)];

            var footerContent = new DefaultTagHelperContent();

            footerContent.AppendHtml(childContent);
            if (DismissText != null)
            {
                footerContent.AppendFormat("<button type='button' class='btn btn-default' data-dismiss='modal'>{0}</button>\n", DismissText);
            }

            modalContext.Footer = footerContent;
            output.SuppressOutput();
        }
        /// <summary>
        ///     Generate the a list for a series of <see cref="OperationMessage" /> items.
        /// </summary>
        /// <param name="messages">The collection of all <see cref="OperationMessage" /> items.</param>
        /// <param name="useTwoLineMode">If the two line mode should be used.</param>
        /// <returns>The generated HTML content which represent as a HTML list.</returns>
        private IHtmlContent GenerateNormalList(IEnumerable <OperationMessage> messages, bool useTwoLineMode)
        {
            var tag = new TagBuilder("ul");

            tag.AddCssClass("list-group");

            var content = new DefaultTagHelperContent();

            foreach (var message in messages)
            {
                content.AppendHtml(GenerateNormalItem(message, useTwoLineMode));
            }

            tag.InnerHtml.AppendHtml(content);

            return(tag);
        }
        public async Task ProcessAsync_AddItemsToContext()
        {
            // Arrange
            var selectContext = new SelectContext(aspFor: null);

            var context = new TagHelperContext(
                tagName: "govuk-select-item",
                allAttributes: new TagHelperAttributeList(),
                items: new Dictionary <object, object>()
            {
                { typeof(SelectContext), selectContext }
            },
                uniqueId: "test");

            var output = new TagHelperOutput(
                "govuk-select-item",
                attributes: new TagHelperAttributeList(),
                getChildContentAsync: (useCachedResult, encoder) =>
            {
                var tagHelperContent = new DefaultTagHelperContent();
                tagHelperContent.AppendHtml(new HtmlString("Item text"));
                return(Task.FromResult <TagHelperContent>(tagHelperContent));
            });

            var tagHelper = new SelectItemTagHelper()
            {
                Disabled = true,
                Selected = true,
                Value    = "value"
            };

            // Act
            await tagHelper.ProcessAsync(context, output);

            // Assert
            Assert.Collection(
                selectContext.Items,
                item =>
            {
                Assert.Equal("Item text", item.Content.RenderToString());
                Assert.True(item.Disabled);
                Assert.True(item.Selected);
                Assert.Equal("value", item.Value);
            });
        }
    public void Append_WithTagHelperContent_MultipleAppends()
    {
        // Arrange
        var tagHelperContent       = new DefaultTagHelperContent();
        var copiedTagHelperContent = new DefaultTagHelperContent();
        var text1    = "Hello";
        var text2    = " World!";
        var expected = "HtmlEncode[[Hello]]HtmlEncode[[ World!]]";

        tagHelperContent.Append(text1);
        tagHelperContent.Append(text2);

        // Act
        copiedTagHelperContent.AppendHtml(tagHelperContent);

        // Assert
        Assert.Equal(expected, copiedTagHelperContent.GetContent(new HtmlTestEncoder()));
    }
Ejemplo n.º 18
0
        public void TestContent()
        {
            var result = new String();

            result.Append("<ng-container *ngIf=\"id_edit.editId !== row.id;else id_edit_a\">");
            result.Append("content");
            result.Append("</ng-container>");

            TagHelperContent content = new DefaultTagHelperContent();

            content.AppendHtml("content");
            var config = new ColumnShareConfig(new TableShareConfig("id"), "a");
            var items  = new Dictionary <object, object> {
                { typeof(ColumnShareConfig), config }
            };

            Assert.Equal(result.ToString(), GetResult(items: items, content: content));
        }
Ejemplo n.º 19
0
        public async Task ProcessAsync_ConditionalContentSpecifiedSetsIsConditional()
        {
            // Arrange
            var checkboxesContext = new CheckboxesContext(
                idPrefix: "prefix",
                resolvedName: "mycheckboxes",
                aspFor: null,
                viewContext: null);

            var context = new TagHelperContext(
                tagName: "govuk-checkboxes-item",
                allAttributes: new TagHelperAttributeList(),
                items: new Dictionary <object, object>()
            {
                { typeof(CheckboxesContext), checkboxesContext }
            },
                uniqueId: "test");

            var output = new TagHelperOutput(
                "govuk-checkboxes-item",
                attributes: new TagHelperAttributeList(),
                getChildContentAsync: (useCachedResult, encoder) =>
            {
                var itemContext = (CheckboxesItemContext)context.Items[typeof(CheckboxesItemContext)];
                itemContext.SetConditional(attributes: null, new HtmlString("Conditional"));

                var tagHelperContent = new DefaultTagHelperContent();
                tagHelperContent.AppendHtml(new HtmlString("Label"));
                return(Task.FromResult <TagHelperContent>(tagHelperContent));
            });

            var tagHelper = new CheckboxesItemTagHelper(new DefaultModelHelper())
            {
                IsChecked = true,
                Value     = "V"
            };

            // Act
            await tagHelper.ProcessAsync(context, output);

            // Assert
            Assert.True(checkboxesContext.IsConditional);
        }
        /// <summary>
        /// Ends the current writing scope that was started by calling <see cref="StartTagHelperWritingScope"/>.
        /// </summary>
        /// <returns>The buffered <see cref="TagHelperContent"/>.</returns>
        public TagHelperContent EndTagHelperWritingScope()
        {
            if (TagHelperScopes.Count == 0)
            {
                throw new InvalidOperationException("There is no active scope to write");
            }

            var scopeInfo = TagHelperScopes.Pop();

            // Get the content written during the current scope.
            var tagHelperContent = new DefaultTagHelperContent();

            tagHelperContent.AppendHtml(scopeInfo.Buffer);

            // Restore previous scope.
            HtmlEncoder        = scopeInfo.HtmlEncoder;
            PageContext.Writer = scopeInfo.Writer;

            return(tagHelperContent);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Ends the current writing scope that was started by calling <see cref="StartTagHelperWritingScope"/>.
        /// </summary>
        /// <returns>The buffered <see cref="TagHelperContent"/>.</returns>
        public TagHelperContent EndTagHelperWritingScope()
        {
            if (TagHelperScopes.Count == 0)
            {
                throw new InvalidOperationException(Resources.RazorPage_ThereIsNoActiveWritingScopeToEnd);
            }

            var scopeInfo = TagHelperScopes.Pop();

            // Get the content written during the current scope.
            var tagHelperContent = new DefaultTagHelperContent();

            tagHelperContent.AppendHtml(scopeInfo.Buffer);

            // Restore previous scope.
            HtmlEncoder        = scopeInfo.HtmlEncoder;
            ViewContext.Writer = scopeInfo.Writer;

            return(tagHelperContent);
        }
Ejemplo n.º 22
0
        public static IHtmlContent SiteMap(this IHtmlHelper htmlHelper, IEnumerable <Menu> menus)
        {
            if (menus == null)
            {
                return(null);
            }
            var html           = new DefaultTagHelperContent();
            var controllerName = Convert.ToString(htmlHelper.ViewContext.RouteData.Values["controller"]);
            var actionName     = Convert.ToString(htmlHelper.ViewContext.RouteData.Values["action"]);

            CurrMenu = menus.FirstOrDefault(a =>
                                            string.Equals(a.ControllerName, controllerName, StringComparison.CurrentCultureIgnoreCase) &&
                                            string.Equals(a.ActionName, actionName, StringComparison.CurrentCultureIgnoreCase));

            var tag = CreateTag(new Menu {
                IsNav = true, ActionName = "Index", ControllerName = "Home", Name = "首页"
            }, CurrMenu != null);
            var builder = Create(menus, CurrMenu);

            return(html.AppendHtml(tag).AppendHtml(builder));
        }
Ejemplo n.º 23
0
        public async Task ProcessAsync_ConditionalContentNotSpecifiedDoesNotSetIsConditional()
        {
            // Arrange
            var radiosContext = new RadiosContext(
                idPrefix: "prefix",
                resolvedName: "myradios",
                viewContext: null,
                aspFor: null);

            var context = new TagHelperContext(
                tagName: "govuk-radios-item",
                allAttributes: new TagHelperAttributeList(),
                items: new Dictionary <object, object>()
            {
                { typeof(RadiosContext), radiosContext }
            },
                uniqueId: "test");

            var output = new TagHelperOutput(
                "govuk-radios-item",
                attributes: new TagHelperAttributeList(),
                getChildContentAsync: (useCachedResult, encoder) =>
            {
                var tagHelperContent = new DefaultTagHelperContent();
                tagHelperContent.AppendHtml(new HtmlString("Label"));
                return(Task.FromResult <TagHelperContent>(tagHelperContent));
            });

            var tagHelper = new RadiosItemTagHelper(new DefaultGovUkHtmlGenerator())
            {
                IsChecked = true,
                Value     = "V"
            };

            // Act
            await tagHelper.ProcessAsync(context, output);

            // Assert
            Assert.False(radiosContext.IsConditional);
        }
        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            output.Attributes.RemoveAll(TagHelperAttributeName);

            if (ShowDismiss)
            {
                output.PreContent.AppendFormat(@"<button type='button' class='btn btn-secondary' data-dismiss='modal'>{0}</button>", DismissText);
            }
            var childContent = await output.GetChildContentAsync();

            var footerContent = new DefaultTagHelperContent();

            if (ShowDismiss)
            {
                _ = footerContent.AppendFormat(@"<button type='button' class='btn btn-secondary' data-dismiss='modal'>{0}</button>", DismissText);
            }
            _ = footerContent.AppendHtml(childContent);
            var modalContext = (ModalContext)context.Items[typeof(ModalTagHelper)];

            modalContext.Footer = footerContent;
            output.SuppressOutput();
        }
Ejemplo n.º 25
0
        public async Task ProcessAsync_GeneratesExpectedOutput_WithDisplayName(
            string displayName,
            string originalChildContent,
            string expectedContent,
            string expectedId)
        {
            // Arrange
            var expectedAttributes = new TagHelperAttributeList
            {
                { "for", expectedId }
            };

            var dataSet = DataSet <TestModel> .Create(_ => _.Text.DisplayName = displayName);

            var tagHelper = GetTagHelper(dataSet._.Text);

            var tagHelperContext = new TagHelperContext(
                tagName: "label",
                allAttributes: new TagHelperAttributeList(),
                items: new Dictionary <object, object>(),
                uniqueId: "test");
            var output = new TagHelperOutput(
                "label",
                new TagHelperAttributeList(),
                getChildContentAsync: (useCachedResult, encoder) =>
            {
                var tagHelperContent = new DefaultTagHelperContent();
                tagHelperContent.AppendHtml(originalChildContent);
                return(Task.FromResult <TagHelperContent>(tagHelperContent));
            });

            // Act
            await tagHelper.ProcessAsync(tagHelperContext, output);

            // Assert
            Assert.Equal(expectedAttributes, output.Attributes);
            Assert.Equal(expectedContent, HtmlContentUtilities.HtmlContentToString(output.Content));
        }
Ejemplo n.º 26
0
        public async Task ProcessAsync_AddsDividerToContextItems()
        {
            // Arrange
            var checkboxesContext = new CheckboxesContext(name: null, aspFor: null);

            var context = new TagHelperContext(
                tagName: "govuk-checkboxes-divider",
                allAttributes: new TagHelperAttributeList(),
                items: new Dictionary <object, object>()
            {
                { typeof(CheckboxesContext), checkboxesContext }
            },
                uniqueId: "test");

            var output = new TagHelperOutput(
                "govuk-checkboxes-divider",
                attributes: new TagHelperAttributeList(),
                getChildContentAsync: (useCachedResult, encoder) =>
            {
                var tagHelperContent = new DefaultTagHelperContent();
                tagHelperContent.AppendHtml(new HtmlString("Divider"));
                return(Task.FromResult <TagHelperContent>(tagHelperContent));
            });

            var tagHelper = new CheckboxesItemDividerTagHelper();

            // Act
            await tagHelper.ProcessAsync(context, output);

            // Assert
            Assert.Collection(
                checkboxesContext.Items,
                item =>
            {
                var divider = Assert.IsType <CheckboxesItemDivider>(item);
                Assert.Equal("Divider", divider.Content.ToString());
            });
        }
    public void CopyTo_CopiesAllItems()
    {
        // Arrange
        var source = new DefaultTagHelperContent();

        source.AppendHtml(new HtmlString("hello"));
        source.Append("Test");

        var items       = new List <object>();
        var destination = new HtmlContentBuilder(items);

        destination.Append("some-content");

        // Act
        source.CopyTo(destination);

        // Assert
        Assert.Equal(3, items.Count);

        Assert.Equal("some-content", Assert.IsType <string>(items[0]));
        Assert.Equal("hello", Assert.IsType <HtmlString>(items[1]).Value);
        Assert.Equal("Test", Assert.IsType <string>(items[2]));
    }
Ejemplo n.º 28
0
        public async Task ProcessAsync_AddsItemToContext()
        {
            // Arrange
            var radiosContext = new RadiosContext(
                idPrefix: "prefix",
                resolvedName: "r",
                viewContext: null,
                aspFor: null);

            var context = new TagHelperContext(
                tagName: "govuk-radios-divider",
                allAttributes: new TagHelperAttributeList(),
                items: new Dictionary <object, object>()
            {
                { typeof(RadiosContext), radiosContext }
            },
                uniqueId: "test");

            var output = new TagHelperOutput(
                "govuk-radios-divider",
                attributes: new TagHelperAttributeList(),
                getChildContentAsync: (useCachedResult, encoder) =>
            {
                var tagHelperContent = new DefaultTagHelperContent();
                tagHelperContent.AppendHtml(new HtmlString("Divider"));
                return(Task.FromResult <TagHelperContent>(tagHelperContent));
            });

            var tagHelper = new RadiosDividerTagHelper();

            // Act
            await tagHelper.ProcessAsync(context, output);

            // Assert
            Assert.Contains(radiosContext.Items, item => item is RadiosItemDivider d && d.Content.AsString() == "Divider");
        }
Ejemplo n.º 29
0
        public async Task ProcessAsync_GeneratesExpectedOutput(
            object model,
            Type containerType,
            Func <object> modelAccessor,
            string propertyPath,
            TagHelperOutputContent tagHelperOutputContent)
        {
            // Arrange
            var expectedTagName    = "not-label";
            var expectedAttributes = new TagHelperAttributeList
            {
                { "class", "form-control" },
                { "for", tagHelperOutputContent.ExpectedId }
            };
            var metadataProvider = new TestModelMetadataProvider();

            var containerMetadata = metadataProvider.GetMetadataForType(containerType);
            var containerExplorer = metadataProvider.GetModelExplorerForType(containerType, model);

            var propertyMetadata = metadataProvider.GetMetadataForProperty(containerType, "Text");
            var modelExplorer    = containerExplorer.GetExplorerForExpression(propertyMetadata, modelAccessor());
            var htmlGenerator    = new TestableHtmlGenerator(metadataProvider);

            var modelExpression = new ModelExpression(propertyPath, modelExplorer);
            var tagHelper       = new LabelTagHelper(htmlGenerator)
            {
                For = modelExpression,
            };
            var expectedPreContent  = "original pre-content";
            var expectedPostContent = "original post-content";

            var tagHelperContext = new TagHelperContext(
                tagName: "not-label",
                allAttributes: new TagHelperAttributeList(),
                items: new Dictionary <object, object>(),
                uniqueId: "test");
            var htmlAttributes = new TagHelperAttributeList
            {
                { "class", "form-control" },
            };
            var output = new TagHelperOutput(
                expectedTagName,
                htmlAttributes,
                getChildContentAsync: (useCachedResult, encoder) =>
            {
                var tagHelperContent = new DefaultTagHelperContent();
                tagHelperContent.AppendHtml(tagHelperOutputContent.OriginalChildContent);
                return(Task.FromResult <TagHelperContent>(tagHelperContent));
            });

            output.PreContent.AppendHtml(expectedPreContent);
            output.PostContent.AppendHtml(expectedPostContent);

            // LabelTagHelper checks IsContentModified so we don't want to forcibly set it if
            // tagHelperOutputContent.OriginalContent is going to be null or empty.
            if (!string.IsNullOrEmpty(tagHelperOutputContent.OriginalContent))
            {
                output.Content.AppendHtml(tagHelperOutputContent.OriginalContent);
            }

            var viewContext = TestableHtmlGenerator.GetViewContext(model, htmlGenerator, metadataProvider);

            tagHelper.ViewContext = viewContext;

            // Act
            await tagHelper.ProcessAsync(tagHelperContext, output);

            // Assert
            Assert.Equal(expectedAttributes, output.Attributes);
            Assert.Equal(expectedPreContent, output.PreContent.GetContent());
            Assert.Equal(
                tagHelperOutputContent.ExpectedContent,
                HtmlContentUtilities.HtmlContentToString(output.Content));
            Assert.Equal(expectedPostContent, output.PostContent.GetContent());
            Assert.Equal(TagMode.StartTagAndEndTag, output.TagMode);
            Assert.Equal(expectedTagName, output.TagName);
        }
Ejemplo n.º 30
0
    public void RenderLinkTags_FallbackHref_WithFileVersion_EncodesAsExpected()
    {
        // Arrange
        var expectedContent = "<link encoded=\"contains \"quotes\"\" " +
                              "href=\"HtmlEncode[[/css/site.css?v=f4OxZX_x_FO5LcGBSKHWXfwtSx-j1ncoSt3SABJtkGk]]\" " +
                              "literal=\"HtmlEncode[[all HTML encoded]]\" " +
                              "mixed=\"HtmlEncode[[HTML encoded]] and contains \"quotes\"\" rel=\"stylesheet\" />" +
                              Environment.NewLine +
                              "<meta name=\"x-stylesheet-fallback-test\" content=\"\" class=\"HtmlEncode[[hidden]]\" /><script>" +
                              "!function(a,b,c,d){var e,f=document,g=f.getElementsByTagName(\"SCRIPT\"),h=g[g.length-1]." +
                              "previousElementSibling,i=f.defaultView&&f.defaultView.getComputedStyle?f.defaultView." +
                              "getComputedStyle(h):h.currentStyle;if(i&&i[a]!==b)for(e=0;e<c.length;e++)f.write('<link " +
                              "href=\"'+c[e]+'\" '+d+\"/>\")}(\"JavaScriptEncode[[visibility]]\",\"JavaScriptEncode[[hidden]]\"," +
                              "[\"JavaScriptEncode[[HtmlEncode[[/fallback.css?v=f4OxZX_x_FO5LcGBSKHWXfwtSx-j1ncoSt3SABJtkGk]]]]\"], " +
                              "\"JavaScriptEncode[[encoded=\"contains \"quotes\"\" literal=\"HtmlEncode[[all HTML encoded]]\" " +
                              "mixed=\"HtmlEncode[[HTML encoded]] and contains \"quotes\"\" rel=\"stylesheet\" ]]\");" +
                              "</script>";
        var mixed = new DefaultTagHelperContent();

        mixed.Append("HTML encoded");
        mixed.AppendHtml(" and contains \"quotes\"");
        var context = MakeTagHelperContext(
            attributes: new TagHelperAttributeList
        {
            { "asp-append-version", "true" },
            { "asp-fallback-href-include", "**/fallback.css" },
            { "asp-fallback-test-class", "hidden" },
            { "asp-fallback-test-property", "visibility" },
            { "asp-fallback-test-value", "hidden" },
            { "encoded", new HtmlString("contains \"quotes\"") },
            { "href", "/css/site.css" },
            { "literal", "all HTML encoded" },
            { "mixed", mixed },
            { "rel", new HtmlString("stylesheet") },
        });
        var output = MakeTagHelperOutput(
            "link",
            attributes: new TagHelperAttributeList
        {
            { "encoded", new HtmlString("contains \"quotes\"") },
            { "literal", "all HTML encoded" },
            { "mixed", mixed },
            { "rel", new HtmlString("stylesheet") },
        });
        var globbingUrlBuilder = new Mock <GlobbingUrlBuilder>(
            new TestFileProvider(),
            Mock.Of <IMemoryCache>(),
            PathString.Empty);

        globbingUrlBuilder.Setup(g => g.BuildUrlList(null, "**/fallback.css", null))
        .Returns(new[] { "/fallback.css" });

        var helper = GetHelper();

        helper.AppendVersion        = true;
        helper.FallbackHrefInclude  = "**/fallback.css";
        helper.FallbackTestClass    = "hidden";
        helper.FallbackTestProperty = "visibility";
        helper.FallbackTestValue    = "hidden";
        helper.GlobbingUrlBuilder   = globbingUrlBuilder.Object;
        helper.Href = "/css/site.css";

        // Act
        helper.Process(context, output);

        // Assert
        Assert.Equal("link", output.TagName);
        Assert.Equal("/css/site.css?v=f4OxZX_x_FO5LcGBSKHWXfwtSx-j1ncoSt3SABJtkGk", output.Attributes["href"].Value);
        var content = HtmlContentUtilities.HtmlContentToString(output, new HtmlTestEncoder());

        Assert.Equal(expectedContent, content);
    }