コード例 #1
0
        public async Task <IHtmlContent> InvokeAsync(Abstractions.IView view)
        {
            // We always need a view name to invoke
            if (string.IsNullOrEmpty(view.ViewName))
            {
                throw new ArgumentNullException(nameof(view.ViewName));
            }

            var result = FindView(view.ViewName);

            if (!result.Success)
            {
                throw new Exception($"A view with the name \"{view.ViewName}\" could not be found!");
            }

            // Log the invocation
            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation($"Attempting to invoke partial view \"{view.ViewName}\".");
            }

            var builder = new HtmlContentBuilder();

            using (var writer = new StringWriter())
            {
                // Render view
                await RenderPartialViewAsync(writer, view.Model, ViewContext.ViewData, result.View);

                // Write results
                builder.WriteTo(writer, HtmlEncoder.Default);
                // Return builder
                return(builder.SetHtmlContent(writer.ToString()));
            }
        }
コード例 #2
0
        private void WriteCheckBoxInLabel(TextWriter writer, ModelExplorer modelExplorer, string name)
        {
            bool IsSubItem = AttributeHelper.IsAttributeDefined <SubItemAttribute>(
                modelExplorer.Metadata.ContainerType,
                modelExplorer.Metadata.PropertyName);
            var labelBuilder = GenerateLabel(IsSubItem);

            var checkboxBuilder = _htmlGenerator.GenerateCheckBox(
                ViewContext,
                modelExplorer,
                name,
                isChecked: Equals(For.Model, true),
                htmlAttributes: null);

            var htmlBuilder = new HtmlContentBuilder();

            htmlBuilder.AppendHtml(labelBuilder.RenderStartTag());
            htmlBuilder.AppendHtml(checkboxBuilder.RenderStartTag());
            htmlBuilder.AppendHtml(labelBuilder.InnerHtml);
            if (!string.IsNullOrEmpty(For.Metadata.Description))
            {
                htmlBuilder.AppendHtml(InformationSpan.FormatSwedish(For.Metadata.Description));
            }
            if (!string.IsNullOrEmpty(HelpLink))
            {
                htmlBuilder.AppendHtml(HelpAnchor.FormatSwedish(HelpLink));
            }
            htmlBuilder.AppendHtml(labelBuilder.RenderEndTag());
            WritePrefix(writer, PrefixAttribute.Position.Value);
            htmlBuilder.WriteTo(writer, _htmlEncoder);
        }
コード例 #3
0
        async Task RenderSeparateBlocks(TextWriter textWriter, IEnumerable <ScriptBlock> blocks)
        {
            foreach (var block in blocks)
            {
                if (block.DisableScriptTag)
                {
                    var builder = new HtmlContentBuilder();
                    builder.AppendHtml(block.Content);
                    builder.WriteTo(textWriter, NullHtmlEncoder.Default);
                    await textWriter.WriteLineAsync();
                }
                else
                {
                    var tagBuilder = new TagBuilder(ScriptTag)
                    {
                        TagRenderMode = TagRenderMode.Normal
                    };

                    tagBuilder.InnerHtml.AppendHtml(block.Content);
                    tagBuilder.MergeAttributes(block.Attributes, replaceExisting: true);
                    tagBuilder.WriteTo(textWriter, NullHtmlEncoder.Default);
                    await textWriter.WriteLineAsync();
                }
            }
        }
コード例 #4
0
ファイル: PartialInvoker.cs プロジェクト: turenc/Plato
        public async Task <IHtmlContent> InvokeAsync(string viewName, object model, ViewDataDictionary viewData)
        {
            // We always need a view name to invoke
            if (string.IsNullOrEmpty(viewName))
            {
                throw new ArgumentNullException(nameof(viewName));
            }

            var builder = new HtmlContentBuilder();
            var result  = FindView(viewName);

            if (!result.Success)
            {
                throw new Exception($"A view with the name \"{viewName}\" could not be found!");
            }

            using (var writer = new StringWriter())
            {
                // Render view
                await RenderPartialViewAsync(writer, model, viewData, result.View);

                // Write results
                builder.WriteTo(writer, HtmlEncoder.Default);
                // Return builder
                return(builder.SetHtmlContent(writer.ToString()));
            }
        }
コード例 #5
0
        public void MoveTo_MovesToBuilder(TagHelperOutput output, string expected)
        {
            // Arrange
            var writer      = new StringWriter();
            var testEncoder = new HtmlTestEncoder();

            var buffer = new HtmlContentBuilder();

            var tagHelperExecutionContext = new TagHelperExecutionContext(
                tagName: output.TagName,
                tagMode: output.TagMode,
                items: new Dictionary <object, object>(),
                uniqueId: string.Empty,
                executeChildContentAsync: () => Task.FromResult(result: true),
                startTagHelperWritingScope: _ => { },
                endTagHelperWritingScope: () => new DefaultTagHelperContent());

            tagHelperExecutionContext.Output = output;

            // Act
            ((IHtmlContentContainer)output).MoveTo(buffer);

            // Assert
            buffer.WriteTo(writer, testEncoder);

            Assert.Equal(string.Empty, output.PreElement.GetContent());
            Assert.Equal(string.Empty, output.PreContent.GetContent());
            Assert.Equal(string.Empty, output.Content.GetContent());
            Assert.Equal(string.Empty, output.PostContent.GetContent());
            Assert.Equal(string.Empty, output.PostElement.GetContent());
            Assert.Empty(output.Attributes);

            Assert.Equal(expected, writer.ToString(), StringComparer.Ordinal);
        }
コード例 #6
0
ファイル: HashtagTagHelper.cs プロジェクト: EveKS/MapMyLuga
        protected string CreateHashTag(string hashTag)
        {
            var content = new HtmlContentBuilder()
                          .AppendHtml($"<a asp-area='' asp-controller='{Controller}' asp-action='{Action}' asp-route-hashTag='{hashTag}' class='btn btn-link btn-hashtag'>{hashTag}</a>");

            using (var writer = new StringWriter(CultureInfo.InvariantCulture))
            {
                content.WriteTo(writer, HtmlEncoder.Default);
                return(writer.ToString());
            }
        }
コード例 #7
0
        public override IHtmlContent GenerateHtml()
        {
            IHtmlContentBuilder contentBuilder = new HtmlContentBuilder();

            contentBuilder.AppendHtml("h1");
            contentBuilder.AppendHtml("h2");
            //contentBuilder.SetContent("This is the content");

            StringWriter writer = new StringWriter();

            contentBuilder.WriteTo(writer, HtmlEncoder.Default);

            return(contentBuilder);
        }
コード例 #8
0
        public void AppendHtml_DoesNotGetWrittenAsEncoded()
        {
            // Arrange
            var content = new HtmlContentBuilder();

            content.AppendHtml("Hello");

            var writer = new StringWriter();

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

            // Assert
            Assert.Equal("Hello", writer.ToString());
        }
コード例 #9
0
        public void WriteTo_WritesAllItems()
        {
            // Arrange
            var content = new HtmlContentBuilder();
            var writer  = new StringWriter();

            content.AppendHtml(new TestHtmlContent("Hello"));
            content.Append("Test");

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

            // Assert
            Assert.Equal(2, content.Count);
            Assert.Equal("Written from TestHtmlContent: HelloHtmlEncode[[Test]]", writer.ToString());
        }
コード例 #10
0
    public void CopyTo_CopiesToBuilder(TagHelperOutput output, string expected)
    {
        // Arrange
        var attributeCount = output.Attributes.Count;

        var writer      = new StringWriter();
        var testEncoder = new HtmlTestEncoder();

        var buffer = new HtmlContentBuilder();

        // Act
        ((IHtmlContentContainer)output).CopyTo(buffer);

        // Assert
        buffer.WriteTo(writer, testEncoder);

        Assert.Equal(attributeCount, output.Attributes.Count);
        Assert.Equal(expected, writer.ToString(), StringComparer.Ordinal);
    }
コード例 #11
0
ファイル: Summary.cs プロジェクト: weedkiller/form-builder
        public override Task <string> RenderAsync(IViewRender viewRender,
                                                  IElementHelper elementHelper,
                                                  string guid,
                                                  Dictionary <string, dynamic> viewModel,
                                                  Page page,
                                                  FormSchema formSchema,
                                                  IWebHostEnvironment environment,
                                                  FormAnswers formAnswers,
                                                  List <object> results = null)
        {
            var htmlContent = new HtmlContentBuilder();
            var pages       = elementHelper.GenerateQuestionAndAnswersList(guid, formSchema);

            htmlContent.AppendHtmlLine("<dl class=\"govuk-summary-list govuk-!-margin-bottom-9\">");
            foreach (var pageSummary in pages)
            {
                foreach (var answer in pageSummary.Answers)
                {
                    htmlContent.AppendHtmlLine("<div class=\"govuk-summary-list__row\">");
                    htmlContent.AppendHtmlLine($"<dt class=\"govuk-summary-list__key\">{answer.Key}</dt>");
                    htmlContent.AppendHtmlLine($"<dd class=\"govuk-summary-list__value\">{answer.Value}</dd>");

                    if (Properties != null && Properties.AllowEditing)
                    {
                        htmlContent.AppendHtmlLine($"<dd class=\"govuk-summary-list__actions\"><a class=\"govuk-link\" href=\"{pageSummary.PageSlug}\">Change <span class=\"govuk-visually-hidden\">{answer.Key}</span></a></dd>");
                    }

                    htmlContent.AppendHtmlLine("</div>");
                }
            }
            htmlContent.AppendHtmlLine("</dl>");

            using (var writer = new StringWriter())
            {
                htmlContent.WriteTo(writer, HtmlEncoder.Default);

                return(Task.FromResult(writer.ToString()));
            }
        }
コード例 #12
0
    public void MoveTo_MovesToBuilder(TagHelperOutput output, string expected)
    {
        // Arrange
        var writer      = new StringWriter();
        var testEncoder = new HtmlTestEncoder();

        var buffer = new HtmlContentBuilder();

        // Act
        ((IHtmlContentContainer)output).MoveTo(buffer);

        // Assert
        buffer.WriteTo(writer, testEncoder);

        Assert.Equal(string.Empty, output.PreElement.GetContent());
        Assert.Equal(string.Empty, output.PreContent.GetContent());
        Assert.Equal(string.Empty, output.Content.GetContent());
        Assert.Equal(string.Empty, output.PostContent.GetContent());
        Assert.Equal(string.Empty, output.PostElement.GetContent());
        Assert.Empty(output.Attributes);

        Assert.Equal(expected, writer.ToString(), StringComparer.Ordinal);
    }
コード例 #13
0
        public override Task <string> RenderAsync(IViewRender viewRender,
                                                  IElementHelper elementHelper,
                                                  string guid,
                                                  Dictionary <string, dynamic> viewModel,
                                                  Page page,
                                                  FormSchema formSchema,
                                                  IWebHostEnvironment environment,
                                                  FormAnswers formAnswers,
                                                  List <object> results = null)
        {
            var htmlContent = new HtmlContentBuilder();

            var paymentSummaryElement = page.Elements.FirstOrDefault(_ => _.Type == EElementType.PaymentSummary);

            htmlContent.AppendHtmlLine($"<p class=\"smbc-body\">The cost is &pound{paymentSummaryElement.Properties.Value}</p>");
            htmlContent.AppendHtmlLine("<p class=\"smbc-body\">Use the button below to continue to our payments page where you&#39;ll need your credit or debit card details.</p>");

            using (var writer = new StringWriter())
            {
                htmlContent.WriteTo(writer, HtmlEncoder.Default);
                return(Task.FromResult(writer.ToString()));
            }
        }
コード例 #14
0
        private void WriteCheckboxGroup(TextWriter writer)
        {
            var htmlBuilder = new HtmlContentBuilder();

            var id = IdOverride ?? For.Name;

            var checkboxGroupBuilder = new TagBuilder("fieldset");

            checkboxGroupBuilder.Attributes.Add("id", id);
            checkboxGroupBuilder.Attributes.Add("for", For.Name);
            checkboxGroupBuilder.Attributes.Add("name", For.Name);

            htmlBuilder.AppendHtml(checkboxGroupBuilder.RenderStartTag());

            var displayName = LabelOverride ?? For.ModelExplorer.Metadata.DisplayName;

            htmlBuilder.AppendHtml($"<legend>{displayName}");
            if (For.ModelExplorer.Metadata.IsRequired ||
                (((RequiredCheckedAttribute)AttributeHelper
                  .GetAttribute <RequiredCheckedAttribute>(For.ModelExplorer.Metadata.ContainerType,
                                                           For.ModelExplorer.Metadata.PropertyName))?.Min > 0))
            {
                htmlBuilder.AppendHtml(RequiredStarSpan);
            }
            htmlBuilder.AppendHtml(InformationSpan.FormatSwedish(For.ModelExplorer.Metadata.Description));
            if (!string.IsNullOrEmpty(HelpLink))
            {
                htmlBuilder.AppendHtml(HelpAnchor.FormatSwedish(HelpLink));
            }
            htmlBuilder.AppendHtml("</legend>");

            var itemsArr = Items.ToArray();

            var selectedItems = ((CheckboxGroup)For.ModelExplorer.Model)?.SelectedItems;

            for (var i = 0; i < itemsArr.Length; i++)
            {
                var item     = itemsArr[i];
                var itemName = $"{id}_{i}";

                bool isChecked   = selectedItems != null && selectedItems.Select(s => s.Value).Contains(item.Value);
                var  checkedAttr = isChecked ? "checked=\"checked\"" : "";

                // Done manually because GenerateCheckbox automatically sets id=For.Name, which it shouldn't
                var inputElem = $"<input data-checkbox-group=\"{For.Name}\" id=\"{itemName}\" name=\"{For.Name}\" type=\"checkbox\" value=\"{item.Value}\" {checkedAttr}/>";

                var labelBuilder = _htmlGenerator.GenerateLabel(
                    ViewContext,
                    For.ModelExplorer,
                    itemName,
                    labelText: item.Text,
                    htmlAttributes: new { @class = "control-label detail-text" });

                htmlBuilder.AppendHtml(labelBuilder.RenderStartTag());
                htmlBuilder.AppendHtml(inputElem);
                htmlBuilder.AppendHtml(labelBuilder.InnerHtml);
                htmlBuilder.AppendHtml(labelBuilder.RenderEndTag());

                htmlBuilder.AppendHtml("<br/>");
            }

            var hiddenBuilder = _htmlGenerator.GenerateHidden(
                ViewContext,
                For.ModelExplorer,
                $"{For.Name}_cbHidden",
                null,
                false,
                new { @class = "force-validation" });

            htmlBuilder.AppendHtml(hiddenBuilder.RenderSelfClosingTag());

            htmlBuilder.AppendHtml(checkboxGroupBuilder.RenderEndTag());

            htmlBuilder.WriteTo(writer, _htmlEncoder);
        }