Exemplo n.º 1
0
    public void Process_WithEmptyForName_Throws()
    {
        // Arrange
        var expectedMessage = "The name of an HTML field cannot be null or empty. Instead use methods " +
                              "Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper.Editor or Microsoft.AspNetCore.Mvc.Rendering." +
                              "IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value.";
        var expectedTagName = "textarea";

        var metadataProvider = new EmptyModelMetadataProvider();
        var htmlGenerator    = new TestableHtmlGenerator(metadataProvider);
        var model            = "model-value";
        var modelExplorer    = metadataProvider.GetModelExplorerForType(typeof(string), model);
        var modelExpression  = new ModelExpression(name: string.Empty, modelExplorer: modelExplorer);
        var viewContext      = TestableHtmlGenerator.GetViewContext(model, htmlGenerator, metadataProvider);
        var tagHelper        = new TextAreaTagHelper(htmlGenerator)
        {
            For         = modelExpression,
            ViewContext = viewContext,
        };

        var context = new TagHelperContext(new TagHelperAttributeList(), new Dictionary <object, object>(), "test");
        var output  = new TagHelperOutput(
            expectedTagName,
            new TagHelperAttributeList(),
            (_, __) => Task.FromResult <TagHelperContent>(new DefaultTagHelperContent()));

        // Act & Assert
        ExceptionAssert.ThrowsArgument(
            () => tagHelper.Process(context, output),
            paramName: "expression",
            exceptionMessage: expectedMessage);
    }
        public async Task ProcessAsync_WithValueAndAspFor_RendersTextAreaWithValue()
        {
            // Arrange
            var modelValue = "Foo value";
            var model      = new Model()
            {
                Foo = modelValue
            };

            var modelExplorer = new EmptyModelMetadataProvider().GetModelExplorerForType(typeof(Model), model)
                                .GetExplorerForProperty(nameof(Model.Foo));
            var viewContext     = new ViewContext();
            var modelExpression = nameof(Model.Foo);

            var modelHelper = new Mock <IModelHelper>();

            modelHelper.Setup(mock => mock.GetModelValue(viewContext, modelExplorer, modelExpression)).Returns(modelValue);

            var context = new TagHelperContext(
                tagName: "govuk-textarea",
                allAttributes: new TagHelperAttributeList(),
                items: new Dictionary <object, object>(),
                uniqueId: "test");

            var output = new TagHelperOutput(
                "govuk-textarea",
                attributes: new TagHelperAttributeList(),
                getChildContentAsync: (useCachedResult, encoder) =>
            {
                var textAreaContext = context.GetContextItem <TextAreaContext>();

                textAreaContext.SetLabel(
                    isPageHeading: false,
                    attributes: null,
                    content: new HtmlString("The label"));

                textAreaContext.SetValue(new HtmlString("Value"));

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

            var tagHelper = new TextAreaTagHelper(modelHelper: modelHelper.Object)
            {
                AspFor      = new ModelExpression(modelExpression, modelExplorer),
                Name        = "my-name",
                ViewContext = viewContext
            };

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

            // Assert
            var element  = output.RenderToElement();
            var textarea = element.GetElementsByTagName("textarea")[0];

            Assert.Equal("Value", textarea.InnerHtml);
        }
        public async Task ProcessAsync_WithError_GeneratesExpectedOutput()
        {
            // Arrange
            var context = new TagHelperContext(
                tagName: "govuk-textarea",
                allAttributes: new TagHelperAttributeList(),
                items: new Dictionary <object, object>(),
                uniqueId: "test");

            var output = new TagHelperOutput(
                "govuk-textarea",
                attributes: new TagHelperAttributeList(),
                getChildContentAsync: (useCachedResult, encoder) =>
            {
                var textAreaContext = context.GetContextItem <TextAreaContext>();

                textAreaContext.SetLabel(
                    isPageHeading: false,
                    attributes: null,
                    content: new HtmlString("The label"));

                textAreaContext.SetHint(
                    attributes: null,
                    content: new HtmlString("The hint"));

                textAreaContext.SetErrorMessage(
                    visuallyHiddenText: null,
                    attributes: null,
                    content: new HtmlString("The error"));

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

            var tagHelper = new TextAreaTagHelper()
            {
                Id   = "my-id",
                Name = "my-name"
            };

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

            // Assert
            var expectedHtml = @"
<div class=""govuk-form-group govuk-form-group--error"">
    <label class=""govuk-label"" for=""my-id"">The label</label>
    <div class=""govuk-hint"" id=""my-id-hint"">The hint</div>
    <p id=""my-id-error"" class=""govuk-error-message"">
        <span class=""govuk-visually-hidden"">Error:</span>
        The error
    </p>
    <textarea class=""govuk-textarea govuk-js-textarea govuk-textarea--error"" id=""my-id"" name=""my-name"" rows=""5"" aria-describedby=""my-id-hint my-id-error""></textarea>
</div>";

            AssertEx.HtmlEqual(expectedHtml, output.RenderToString());
        }
Exemplo n.º 4
0
        private async Task <TagHelperOutput> CreateTextArea(TagHelperContext context)
        {
            var tagHelper = new TextAreaTagHelper(Generator);

            tagHelper.For         = For;
            tagHelper.ViewContext = ViewContext;
            var tagHelperOutput = TagHelperExtension.CreateTagHelperOutput("textarea");
            await tagHelper.ProcessAsync(context, tagHelperOutput);

            return(tagHelperOutput);
        }
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            string input = "";

            var helper = new TextAreaTagHelper(Generator);

            helper.ViewContext = ViewContext;
            helper.For         = Value;

            helper.Init(context);
            helper.Process(context, output);

            using (var writer = new StringWriter())
            {
                output.TagName = "textarea";
                output.Attributes.Add("class", "form-control");
                output.Attributes.Add("rows", "4");

                output.WriteTo(writer, HtmlEncoder.Default);
                input = writer.ToString();
            }

            output.Attributes.Clear();
            output.PostContent.Clear();
            output.Content.Clear();

            string req = (input.IndexOf("data-val-required") > -1) ? "<span class='required'>*</span>" : "";

            var label        = Label ?? Value?.Metadata?.DisplayName ?? Value?.Name ?? "";
            var labelContent = $"<label for='{Value.Name}' class='col-sm-4 col-form-label'>{req}{label}</label>";

            var validateBuilder = Generator.GenerateValidationMessage(
                ViewContext,
                Value.ModelExplorer,
                Value.Name,
                message: null,
                tag: null,
                htmlAttributes: null);

            var divBuilder = new TagBuilder("div");

            divBuilder.AddCssClass("col-sm-8");

            divBuilder.InnerHtml.AppendHtml(input);
            divBuilder.InnerHtml.AppendHtml(validateBuilder);

            output.TagName = "div";
            output.Attributes.Add("class", "form-group row");

            output.Content.AppendHtml(labelContent);
            output.Content.AppendHtml(divBuilder);
        }
Exemplo n.º 6
0
        public TagHelperOutput GenerateTextAreaTagHelper(ModelExpression f, int rows)
        {
            var tagHelper = new TextAreaTagHelper(generator)
            {
                For         = f,
                Name        = f.Name,
                ViewContext = viewContext
            };

            var tagOutput = GenerateTagHelperCore(f, tagHelper, "textarea", TagMode.StartTagAndEndTag);

            tagOutput.Attributes.Add(new TagHelperAttribute("rows", rows));
            return(tagOutput);
        }
Exemplo n.º 7
0
        public async Task ProcessAsync_GeneratesExpectedOutput()
        {
            // Arrange
            var context = new TagHelperContext(
                tagName: "govuk-textarea",
                allAttributes: new TagHelperAttributeList(),
                items: new Dictionary <object, object>(),
                uniqueId: "test");

            var output = new TagHelperOutput(
                "govuk-textarea",
                attributes: new TagHelperAttributeList(),
                getChildContentAsync: (useCachedResult, encoder) =>
            {
                var formGroupContext = (TextAreaBuilder)context.Items[typeof(FormGroupBuilder)];
                formGroupContext.TrySetLabel(
                    isPageHeading: false,
                    attributes: null,
                    content: new HtmlString("The label"));
                formGroupContext.TrySetElementContent(new HtmlString("The content"));

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

            var tagHelper = new TextAreaTagHelper(new DefaultGovUkHtmlGenerator())
            {
                Id           = "my-id",
                DescribedBy  = "describedby",
                Name         = "my-id",
                Rows         = 6,
                Autocomplete = "username"
            };

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

            // Assert
            var html     = output.AsString();
            var node     = HtmlNode.CreateNode(html);
            var textarea = node.ChildNodes.FindFirst("textarea");

            Assert.Equal(
                "<textarea aria-describedby=\"describedby\" autocomplete=\"username\" class=\"govuk-textarea\" id=\"my-id\" name=\"my-id\" rows=\"6\">" +
                "The content" +
                "</textarea>",
                textarea.OuterHtml);
        }
Exemplo n.º 8
0
        public async Task ProcessAsync_HasErrorClassWhenErrorSpecified()
        {
            // Arrange
            var context = new TagHelperContext(
                tagName: "govuk-textarea",
                allAttributes: new TagHelperAttributeList(),
                items: new Dictionary <object, object>(),
                uniqueId: "test");

            var output = new TagHelperOutput(
                "govuk-textarea",
                attributes: new TagHelperAttributeList(),
                getChildContentAsync: (useCachedResult, encoder) =>
            {
                var formGroupContext = (TextAreaBuilder)context.Items[typeof(FormGroupBuilder)];
                formGroupContext.TrySetLabel(
                    isPageHeading: false,
                    attributes: null,
                    content: new HtmlString("The label"));
                formGroupContext.TrySetErrorMessage(
                    visuallyHiddenText: null,
                    attributes: null,
                    content: new HtmlString("Error"));
                formGroupContext.TrySetElementContent(new HtmlString("The content"));

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

            var tagHelper = new TextAreaTagHelper(new DefaultGovUkHtmlGenerator())
            {
                Id           = "my-id",
                DescribedBy  = "describedby",
                Name         = "my-id",
                Rows         = 6,
                Autocomplete = "username"
            };

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

            // Assert
            var html = output.AsString();
            var node = HtmlNode.CreateNode(html);

            Assert.Contains("govuk-textarea--error", node.ChildNodes.FindFirst("textarea").GetCssClasses());
        }
Exemplo n.º 9
0
    public void Process_WithEmptyForName_DoesNotThrow_WithName()
    {
        // Arrange
        var expectedAttributeValue = "-expression-";
        var expectedContent        = Environment.NewLine + "HtmlEncode[[model-value]]";
        var expectedTagName        = "textarea";

        var metadataProvider = new EmptyModelMetadataProvider();
        var htmlGenerator    = new TestableHtmlGenerator(metadataProvider);
        var model            = "model-value";
        var modelExplorer    = metadataProvider.GetModelExplorerForType(typeof(string), model);
        var modelExpression  = new ModelExpression(name: string.Empty, modelExplorer: modelExplorer);
        var viewContext      = TestableHtmlGenerator.GetViewContext(model, htmlGenerator, metadataProvider);
        var tagHelper        = new TextAreaTagHelper(htmlGenerator)
        {
            For         = modelExpression,
            Name        = expectedAttributeValue,
            ViewContext = viewContext,
        };

        var attributes = new TagHelperAttributeList
        {
            { "name", expectedAttributeValue },
        };

        var context = new TagHelperContext(attributes, new Dictionary <object, object>(), "test");
        var output  = new TagHelperOutput(
            expectedTagName,
            new TagHelperAttributeList(),
            (_, __) => Task.FromResult <TagHelperContent>(new DefaultTagHelperContent()));

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

        // Assert
        Assert.Equal(expectedTagName, output.TagName);
        Assert.Equal(expectedContent, HtmlContentUtilities.HtmlContentToString(output.Content));

        var attribute = Assert.Single(output.Attributes);

        Assert.Equal("name", attribute.Name);
        Assert.Equal(expectedAttributeValue, attribute.Value);
    }
Exemplo n.º 10
0
        protected virtual TagHelper GetInputTagHelper(TagHelperContext context, TagHelperOutput output)
        {
            if (TagHelper.AspFor.ModelExplorer.GetAttribute <TextArea>() != null)
            {
                var textAreaTagHelper = new TextAreaTagHelper(_generator)
                {
                    For         = TagHelper.AspFor,
                    ViewContext = TagHelper.ViewContext
                };

                if (!TagHelper.Name.IsNullOrEmpty())
                {
                    textAreaTagHelper.Name = TagHelper.Name;
                }

                return(textAreaTagHelper);
            }

            var inputTagHelper = new InputTagHelper(_generator)
            {
                For           = TagHelper.AspFor,
                InputTypeName = TagHelper.InputTypeName,
                ViewContext   = TagHelper.ViewContext
            };

            if (!TagHelper.Format.IsNullOrEmpty())
            {
                inputTagHelper.Format = TagHelper.Format;
            }

            if (!TagHelper.Name.IsNullOrEmpty())
            {
                inputTagHelper.Name = TagHelper.Name;
            }

            if (!TagHelper.Value.IsNullOrEmpty())
            {
                inputTagHelper.Value = TagHelper.Value;
            }

            return(inputTagHelper);
        }
        public async Task ProcessAsync_WithValue_RendersTextAreaWithValue()
        {
            // Arrange
            var context = new TagHelperContext(
                tagName: "govuk-textarea",
                allAttributes: new TagHelperAttributeList(),
                items: new Dictionary <object, object>(),
                uniqueId: "test");

            var output = new TagHelperOutput(
                "govuk-textarea",
                attributes: new TagHelperAttributeList(),
                getChildContentAsync: (useCachedResult, encoder) =>
            {
                var textAreaContext = context.GetContextItem <TextAreaContext>();

                textAreaContext.SetLabel(
                    isPageHeading: false,
                    attributes: null,
                    content: new HtmlString("The label"));

                textAreaContext.SetValue(new HtmlString("Value"));

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

            var tagHelper = new TextAreaTagHelper()
            {
                Name = "my-name"
            };

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

            // Assert
            var element  = output.RenderToElement();
            var textarea = element.GetElementsByTagName("textarea")[0];

            Assert.Equal("Value", textarea.InnerHtml);
        }
Exemplo n.º 12
0
        public async Task ProcessAsync_NoContentOrAspForThrowsInvalidOperationException()
        {
            // Arrange
            var context = new TagHelperContext(
                tagName: "govuk-textarea",
                allAttributes: new TagHelperAttributeList(),
                items: new Dictionary <object, object>(),
                uniqueId: "test");

            var output = new TagHelperOutput(
                "govuk-textarea",
                attributes: new TagHelperAttributeList(),
                getChildContentAsync: (useCachedResult, encoder) =>
            {
                var formGroupContext = (TextAreaBuilder)context.Items[typeof(FormGroupBuilder)];
                formGroupContext.TrySetLabel(
                    isPageHeading: false,
                    attributes: null,
                    content: new HtmlString("The label"));

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

            var tagHelper = new TextAreaTagHelper(new DefaultGovUkHtmlGenerator())
            {
                Id           = "my-id",
                DescribedBy  = "describedby",
                Name         = "my-id",
                Rows         = 6,
                Autocomplete = "username"
            };

            // Act & Assert
            var ex = await Assert.ThrowsAsync <InvalidOperationException>(() => tagHelper.ProcessAsync(context, output));

            Assert.Equal("Content must be specified when the 'asp-for' attribute is not specified.", ex.Message);
        }
Exemplo n.º 13
0
    public async Task Process_GeneratesExpectedOutput(
        object container,
        Type containerType,
        object model,
        NameAndId nameAndId,
        string expectedContent)
    {
        // Arrange
        var expectedAttributes = new TagHelperAttributeList
        {
            { "class", "form-control" },
            { "id", nameAndId.Id },
            { "name", nameAndId.Name },
            { "valid", "from validation attributes" },
        };
        var expectedTagName = "not-textarea";

        var metadataProvider = new TestModelMetadataProvider();

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

        var propertyMetadata = metadataProvider.GetMetadataForProperty(containerType, "Text");
        var modelExplorer    = containerExplorer.GetExplorerForExpression(propertyMetadata, model);

        var htmlGenerator = new TestableHtmlGenerator(metadataProvider)
        {
            ValidationAttributes =
            {
                { "valid", "from validation attributes" },
            }
        };

        // Property name is either nameof(Model.Text) or nameof(NestedModel.Text).
        var modelExpression = new ModelExpression(nameAndId.Name, modelExplorer);
        var tagHelper       = new TextAreaTagHelper(htmlGenerator)
        {
            For = modelExpression,
        };

        var tagHelperContext = new TagHelperContext(
            tagName: "text-area",
            allAttributes: new TagHelperAttributeList(
                Enumerable.Empty <TagHelperAttribute>()),
            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.SetContent("Something");
            return(Task.FromResult <TagHelperContent>(tagHelperContent));
        })
        {
            TagMode = TagMode.SelfClosing,
        };

        output.Content.SetContent("original content");

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

        tagHelper.ViewContext = viewContext;

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

        // Assert
        Assert.Equal(TagMode.SelfClosing, output.TagMode);
        Assert.Equal(expectedAttributes, output.Attributes);
        Assert.Equal(expectedContent, HtmlContentUtilities.HtmlContentToString(output.Content));
        Assert.Equal(expectedTagName, output.TagName);
    }
Exemplo n.º 14
0
 /// <summary>
 /// 测试初始化
 /// </summary>
 public TextAreaTagHelperTest(ITestOutputHelper output)
 {
     _output           = output;
     _component        = new TextAreaTagHelper();
     Config.IsValidate = false;
 }