public static void AddCssClass(this TagHelperAttributeList attributeList, string cssClass)
        {
            const string classAttribute = "class";

            var existingCssClassValue = attributeList
                                        .FirstOrDefault(x => x.Name == classAttribute)?.Value.ToString();

            // If the class attribute doesn't exist, or the class attribute
            // value is empty, just add the CSS class to class attribute
            if (String.IsNullOrEmpty(existingCssClassValue))
            {
                attributeList.SetAttribute(classAttribute, cssClass);
            }

            // Here I use Regular Expression to check if the existing css class
            // value has the css class already. If yes, you don't need to add
            // that css class again. Otherwise you just add the css class along
            // with the existing value.
            // \b indicates a word boundary, as you only want to check if
            // the css class exists as a whole word.
            else if (!Regex.IsMatch(existingCssClassValue, $@"\b{ cssClass }\b", RegexOptions.IgnoreCase))
            {
                attributeList.SetAttribute(classAttribute, $"{ cssClass } { existingCssClassValue }");
            }
        }
 static public void SetHtmlStringAttribute(this TagHelperAttributeList attributes, string name, object value)
 {
     if (value?.GetType() == typeof(string))
     {
         attributes.SetAttribute(name, new HtmlString((string)value));
     }
     else
     {
         attributes.SetAttribute(name, value);
     }
 }
示例#3
0
        public static void SetAttributeDictionary(this TagHelperAttributeList attrList, string id, RouteValueDictionary newAttrs)
        {
            attrList.SetAttribute("spf-attr", "");

            foreach (var d in newAttrs)
            {
                if (!string.IsNullOrEmpty(id))
                {
                    attrList.SetAttribute(d.Key, d.Value);
                }
                attrList.SetAttribute("spf-attr-" + d.Key, d.Value);
            }
        }
示例#4
0
 public static void AddClass(this TagHelperAttributeList attrs, string append_class)
 {
     if (attrs.ContainsName("class"))
     {
         append_class += " " + attrs["class"].Value;
     }
     attrs.SetAttribute("class", append_class);
 }
        public static void AppendCssClass(this TagHelperAttributeList list, string newCssClasses)
        {
            string oldCssClasses = list["class"]?.Value?.ToString();
            string cssClasses    = (string.IsNullOrEmpty(oldCssClasses)) ?
                                   newCssClasses : $"{oldCssClasses}{newCssClasses}";

            list.SetAttribute("class", cssClasses);
        }
示例#6
0
        /// <summary>
        /// Adds a <see cref="TagHelperAttribute"/> with <paramref name="name"/> and <paramref name="value"/> to the end of the collection,
        /// but only if the attribute does not exist.
        /// </summary>
        /// <param name="name">The <see cref="TagHelperAttribute.Name"/> of the <see cref="TagHelperAttribute"/> to set.</param>
        /// <param name="value">The <see cref="TagHelperAttribute.Value"/> to set.</param>
        /// <param name="ignoreNull"><c>false</c> = don't render attribute if value is null.</param>
        /// <remarks><paramref name="name"/> is compared case-insensitively.</remarks>
        public static void SetAttributeNoReplace(this TagHelperAttributeList attributes, string name, object value, bool ignoreNull = true)
        {
            Guard.NotEmpty(name, nameof(name));

            if (!attributes.ContainsName(name) && (value != null || !ignoreNull))
            {
                attributes.SetAttribute(name, value);
            }
        }
示例#7
0
        /// <summary>
        /// Adds a <see cref="TagHelperAttribute"/> with <paramref name="name"/> and the value of <paramref name="valueAccessor"/> to the end of the collection,
        /// but only if the attribute does not exist.
        /// </summary>
        /// <param name="name">
        /// The <see cref="TagHelperAttribute.Name"/> of the <see cref="TagHelperAttribute"/> to set.
        /// </param>
        /// <param name="valueAccessor">
        /// The <see cref="TagHelperAttribute.Value"/> to set.
        /// </param>
        /// <remarks><paramref name="name"/> is compared case-insensitively.</remarks>
        public static void SetAttributeNoReplace(this TagHelperAttributeList attributes, string name, Func <object> valueAccessor)
        {
            Guard.NotEmpty(name, nameof(name));

            if (!attributes.ContainsName(name))
            {
                attributes.SetAttribute(name, valueAccessor());
            }
        }
示例#8
0
        /// <summary>
        /// Adds a class to a tag, if it is not already there (case sensitive)
        /// </summary>
        /// <param name="attributes">The attribute list to add the class to</param>
        /// <param name="htmlClass">The class to add to the tag</param>
        /// <remarks>Keep checking to see if this or similar is added to the framework</remarks>
        public static void AddClass(this TagHelperAttributeList attributes, string htmlClass)
        {
            attributes.TryGetAttribute("class", out var classAttribute);
            var classes = classAttribute?.Value?.ToString();

            if (string.IsNullOrWhiteSpace(classes))
            {
                attributes.SetAttribute("class", htmlClass);
                return;
            }

            var classList = classes.Split(' ', StringSplitOptions.RemoveEmptyEntries);

            if (!classList.Contains(htmlClass, StringComparer.Ordinal))
            {
                attributes.SetAttribute("class", new HtmlString($"{classes} {htmlClass}"));
            }
        }
示例#9
0
        /// <summary>
        /// Copies all attributes from <paramref name="attributes"/> to <paramref name="target"/>
        /// overriding any existing attribute.
        /// </summary>
        public static void CopyTo(this AttributeDictionary attributes, TagHelperAttributeList target)
        {
            Guard.NotNull(attributes, nameof(attributes));
            Guard.NotNull(target, nameof(target));

            foreach (var attr in attributes)
            {
                target.SetAttribute(attr.Key, attr.Value);
            }
        }
示例#10
0
        public static void MergeClassAttributeValue(this TagHelperAttributeList attributes, string newClassValue)
        {
            string classValue = newClassValue;

            if (attributes.ContainsName("class"))
            {
                classValue = $"{attributes["class"].Value} {classValue}";
            }
            attributes.SetAttribute("class", classValue);
        }
 public static void AddOrUpdate(this TagHelperAttributeList attributes, string name, object value)
 {
     if (attributes.ContainsName(name))
     {
         attributes.SetAttribute(name, value);
     }
     else
     {
         attributes.Add(name, value);
     }
 }
        public static void RemoveClass(this TagHelperAttributeList attributes, string className)
        {
            var classAttribute = attributes["class"];

            if (classAttribute == null)
            {
                return;
            }

            //Can be optimized?
            attributes.SetAttribute("class", classAttribute.Value.ToString().Split(' ').RemoveAll(c => c == className).JoinAsString(" "));
        }
示例#13
0
        public void ApplyTo(TagHelperAttributeList target)
        {
            Guard.NotNull(target, nameof(target));

            if (_list.Count == 0)
            {
                target.RemoveAll("class");
            }
            else
            {
                target.SetAttribute("class", string.Join(' ', _list));
            }
        }
示例#14
0
        /// <summary>
        /// Adds a <see cref="TagHelperAttribute"/> with <paramref name="name"/> and the value of <paramref name="valueAccessor"/> to the end of the collection,
        /// but only if the attribute does not exist.
        /// </summary>
        /// <param name="name">The <see cref="TagHelperAttribute.Name"/> of the <see cref="TagHelperAttribute"/> to set.</param>
        /// <param name="valueAccessor">The <see cref="TagHelperAttribute.Value"/> to set.</param>
        /// <param name="ignoreNull"><c>false</c> = don't render attribute if value is null.</param>
        /// <remarks><paramref name="name"/> is compared case-insensitively.</remarks>
        public static void SetAttributeNoReplace(this TagHelperAttributeList attributes, string name, Func <object> valueAccessor, bool ignoreNull = true)
        {
            Guard.NotEmpty(name, nameof(name));

            if (!attributes.ContainsName(name))
            {
                var value = valueAccessor();
                if (value != null || !ignoreNull)
                {
                    attributes.SetAttribute(name, valueAccessor());
                }
            }
        }
        public static void AddClass(this TagHelperAttributeList attributes, string className)
        {
            var classAttribute = attributes["class"];

            if (classAttribute == null)
            {
                attributes.Add("class", className);
            }
            else
            {
                //TODO: Check if it's already added before!
                attributes.SetAttribute("class", classAttribute.Value + " " + className);
            }
        }
    public void StringIndexer_SetsAttributeAtExpectedLocation(
        IEnumerable <TagHelperAttribute> initialAttributes,
        string keyToSet,
        object setValue,
        IEnumerable <TagHelperAttribute> expectedAttributes)
    {
        // Arrange
        var attributes = new TagHelperAttributeList(initialAttributes);

        // Act
        attributes.SetAttribute(keyToSet, setValue);

        // Assert
        Assert.Equal(expectedAttributes, attributes, CaseSensitiveTagHelperAttributeComparer.Default);
    }
        public static void AddOrUpdate(this TagHelperAttributeList attributes, string name, Func <object, object> valueFunc)
        {
            object value;

            if (attributes.ContainsName(name))
            {
                value = valueFunc(attributes[name].Value);
                attributes.SetAttribute(name, value);
            }
            else
            {
                value = valueFunc(null);
                attributes.Add(name, value);
            }
        }
        /// <summary>
        /// TODO document
        /// </summary>
        /// <param name="attributes"></param>
        /// <param name="attribute"></param>
        /// <param name="value"></param>
        public static void AppendToAttribute(this TagHelperAttributeList attributes, string attribute, string value)
        {
            var hasAttribute = attributes.TryGetAttribute(attribute, out var classAttribute);

            var existingValue = "";

            if (hasAttribute)
            {
                existingValue = classAttribute.Value.ToString() + " ";
            }

            existingValue += value;

            attributes.SetAttribute(attribute, existingValue);
        }
示例#19
0
        private static void AddInAttributeValue(TagHelperAttributeList attrList, string name, char separator, string value, bool prepend = false)
        {
            if (!attrList.TryGetAttribute(name, out var attribute))
            {
                attrList.Add(new TagHelperAttribute(name, value));
            }
            else
            {
                var arr      = attribute.Value.ToString().Trim().Tokenize(new[] { separator }, StringSplitOptions.RemoveEmptyEntries);
                var arrValue = value.Trim().Tokenize(new[] { separator }, StringSplitOptions.RemoveEmptyEntries);

                arr = prepend ? arrValue.Union(arr) : arr.Union(arrValue);

                attrList.SetAttribute(name, string.Join(separator, arr));
            }
        }
示例#20
0
        public static async Task <string> RenderAsync(SvgTagHelperConfiguration config, string iconName, string classes)
        {
            var svg = new SvgTagHelper(config)
            {
                Name = iconName
            };

            TagHelperAttributeList attributes = null;

            if (!string.IsNullOrEmpty(classes))
            {
                attributes = new TagHelperAttributeList();
                attributes.SetAttribute("class", classes);
            }

            var content = await svg.RenderTagHelperAsync(attributes);

            return(content);
        }
示例#21
0
    public static void RemoveClass(this TagHelperAttributeList attributes, string className)
    {
        if (string.IsNullOrWhiteSpace(className))
        {
            return;
        }

        var classAttribute = attributes["class"];

        if (classAttribute == null)
        {
            return;
        }

        var classList = classAttribute.Value.ToString().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();

        classList.RemoveAll(c => c == className);

        attributes.SetAttribute("class", classList.JoinAsString(" "));
    }
示例#22
0
    public static void AddClass(this TagHelperAttributeList attributes, string className)
    {
        if (string.IsNullOrWhiteSpace(className))
        {
            return;
        }

        var classAttribute = attributes["class"];

        if (classAttribute == null)
        {
            attributes.Add("class", className);
        }
        else
        {
            var existingClasses = classAttribute.Value.ToString().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            existingClasses.AddIfNotContains(className);
            attributes.SetAttribute("class", string.Join(" ", existingClasses));
        }
    }
        public static bool AddClass(this TagHelperAttributeList attributes, string className)
        {
            if (string.IsNullOrWhiteSpace(className))
            {
                throw new ArgumentNullException(nameof(className));
            }

            if (!attributes.TryGetAttribute("class", out TagHelperAttribute classAttribute))
            {
                attributes.Add(new TagHelperAttribute("class", className));
                return(true);
            }

            if (attributes.ContainsClass(className))
            {
                return(false);
            }

            string classes = classAttribute.Value.ToString();

            attributes.SetAttribute("class", string.Join(" ", className, classes));
            return(true);
        }
示例#24
0
        public static TagHelperAttributeList AddOrAppendAttribute(
            this TagHelperAttributeList tagAttributesList,
            string name,
            string attrValue,
            bool appendFirst                  = false,
            bool checkForDuplicates           = false,
            Func <string, bool> dontAddIfPred = null)
        {
            if (name.IsNulle())
            {
                throw new ArgumentNullException();
            }
            if (tagAttributesList == null)
            {
                throw new ArgumentNullException();
            }

            if (attrValue == null)
            {
                return(tagAttributesList);
            }

            TagHelperAttribute attr = tagAttributesList.IsNulle()
                                ? null
                                : tagAttributesList.FirstN(t => t.Name == name);

            if (attr != null)
            {
                string attrValStr = attr.Value?.ToString();
                if (attrValStr.IsNulle())
                {
                    attr = null;
                }
                else
                {
                    if (dontAddIfPred != null && dontAddIfPred.Invoke(attrValStr))
                    {
                        return(tagAttributesList);
                    }

                    attrValue = appendFirst
                                                ? $"{attrValue} {attrValStr}"
                                                : $"{attrValStr} {attrValue}";
                }
            }

            attrValue = attrValue.TrimIfNeeded();

            if (checkForDuplicates && attr != null)
            {
                // so only have to do this check if attribute already exists, that single check will GREATLY improv perf, removing a needless case
                attrValue = attrValue
                            .SplitAndRemoveWhiteSpaceEntries(_whiteSpSeparators)
                            .Distinct()
                            .JoinToString(" ");
            }

            tagAttributesList.SetAttribute(name, attrValue);

            return(tagAttributesList);
        }
示例#25
0
        public async Task ProcessAsync_CallsGenerateTextBox_WithExpectedParameters(
            string dataTypeName,
            string inputTypeName,
            string model)
        {
            // Arrange
            var contextAttributes = new TagHelperAttributeList
            {
                { "class", "form-control" },
            };
            if (!string.IsNullOrEmpty(inputTypeName))
            {
                contextAttributes.SetAttribute("type", inputTypeName);  // Support restoration of type attribute, if any.
            }

            var expectedAttributes = new TagHelperAttributeList
            {
                { "class", "form-control text-control" },
                { "type", inputTypeName ?? "text" },        // Generator restores type attribute; adds "text" if none.
            };
            var expectedPreContent = "original pre-content";
            var expectedContent = "original content";
            var expectedPostContent = "original post-content";
            var expectedTagName = "not-input";

            var context = new TagHelperContext(
                allAttributes: contextAttributes,
                items: new Dictionary<object, object>(),
                uniqueId: "test");
            var originalAttributes = new TagHelperAttributeList
            {
                { "class", "form-control" },
            };
            var output = new TagHelperOutput(
                expectedTagName,
                originalAttributes,
                getChildContentAsync: (useCachedResult, encoder) =>
                {
                    var tagHelperContent = new DefaultTagHelperContent();
                    tagHelperContent.SetContent("Something");
                    return Task.FromResult<TagHelperContent>(tagHelperContent);
                })
            {
                TagMode = TagMode.StartTagOnly,
            };
            output.PreContent.SetContent(expectedPreContent);
            output.Content.SetContent(expectedContent);
            output.PostContent.SetContent(expectedPostContent);

            var metadataProvider = new TestModelMetadataProvider();
            metadataProvider.ForProperty<Model>("Text").DisplayDetails(dd => dd.DataTypeName = dataTypeName);

            var htmlGenerator = new Mock<IHtmlGenerator>(MockBehavior.Strict);
            var tagHelper = GetTagHelper(
                htmlGenerator.Object,
                model,
                nameof(Model.Text),
                metadataProvider: metadataProvider);
            tagHelper.InputTypeName = inputTypeName;

            var tagBuilder = new TagBuilder("input")
            {
                Attributes =
                {
                    { "class", "text-control" },
                },
            };
            htmlGenerator
                .Setup(mock => mock.GenerateTextBox(
                    tagHelper.ViewContext,
                    tagHelper.For.ModelExplorer,
                    tagHelper.For.Name,
                    model,      // value
                    null,       // format
                    It.Is<Dictionary<string, object>>(m => m.ContainsKey("type"))))      // htmlAttributes
                .Returns(tagBuilder)
                .Verifiable();

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

            // Assert
            htmlGenerator.Verify();

            Assert.Equal(TagMode.StartTagOnly, output.TagMode);
            Assert.Equal(expectedAttributes, output.Attributes);
            Assert.Equal(expectedPreContent, output.PreContent.GetContent());
            Assert.Equal(expectedContent, output.Content.GetContent());
            Assert.Equal(expectedPostContent, output.PostContent.GetContent());
            Assert.Equal(expectedTagName, output.TagName);
        }
示例#26
0
        public async Task ProcessAsync_CallsGenerateTextBox_WithExpectedParameters(
            string dataTypeName,
            string inputTypeName,
            string model)
        {
            // Arrange
            var contextAttributes = new TagHelperAttributeList
            {
                { "class", "form-control" },
            };

            if (!string.IsNullOrEmpty(inputTypeName))
            {
                contextAttributes.SetAttribute("type", inputTypeName);  // Support restoration of type attribute, if any.
            }

            var expectedAttributes = new TagHelperAttributeList
            {
                { "class", "form-control text-control" },
                { "type", inputTypeName ?? "text" },        // Generator restores type attribute; adds "text" if none.
            };
            var expectedPreContent  = "original pre-content";
            var expectedContent     = "original content";
            var expectedPostContent = "original post-content";
            var expectedTagName     = "not-input";

            var context = new TagHelperContext(
                allAttributes: contextAttributes,
                items: new Dictionary <object, object>(),
                uniqueId: "test");
            var originalAttributes = new TagHelperAttributeList
            {
                { "class", "form-control" },
            };
            var output = new TagHelperOutput(
                expectedTagName,
                originalAttributes,
                getChildContentAsync: (useCachedResult, encoder) =>
            {
                var tagHelperContent = new DefaultTagHelperContent();
                tagHelperContent.SetContent("Something");
                return(Task.FromResult <TagHelperContent>(tagHelperContent));
            })
            {
                TagMode = TagMode.StartTagOnly,
            };

            output.PreContent.SetContent(expectedPreContent);
            output.Content.SetContent(expectedContent);
            output.PostContent.SetContent(expectedPostContent);

            var metadataProvider = new TestModelMetadataProvider();

            metadataProvider.ForProperty <Model>("Text").DisplayDetails(dd => dd.DataTypeName = dataTypeName);

            var htmlGenerator = new Mock <IHtmlGenerator>(MockBehavior.Strict);
            var tagHelper     = GetTagHelper(
                htmlGenerator.Object,
                model,
                nameof(Model.Text),
                metadataProvider: metadataProvider);

            tagHelper.InputTypeName = inputTypeName;

            var tagBuilder = new TagBuilder("input")
            {
                Attributes =
                {
                    { "class", "text-control" },
                },
            };

            htmlGenerator
            .Setup(mock => mock.GenerateTextBox(
                       tagHelper.ViewContext,
                       tagHelper.For.ModelExplorer,
                       tagHelper.For.Name,
                       model,                                                             // value
                       null,                                                              // format
                       It.Is <Dictionary <string, object> >(m => m.ContainsKey("type")))) // htmlAttributes
            .Returns(tagBuilder)
            .Verifiable();

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

            // Assert
            htmlGenerator.Verify();

            Assert.Equal(TagMode.StartTagOnly, output.TagMode);
            Assert.Equal(expectedAttributes, output.Attributes);
            Assert.Equal(expectedPreContent, output.PreContent.GetContent());
            Assert.Equal(expectedContent, output.Content.GetContent());
            Assert.Equal(expectedPostContent, output.PostContent.GetContent());
            Assert.Equal(expectedTagName, output.TagName);
        }
示例#27
0
        public async Task ProcessAsync_CallsGenerateRadioButton_WithExpectedParameters(
            string inputTypeName,
            string model)
        {
            // Arrange
            var value             = "match"; // Real generator would use this for comparison with For.Metadata.Model.
            var contextAttributes = new TagHelperAttributeList
            {
                { "class", "form-control" },
                { "value", value },
            };

            if (!string.IsNullOrEmpty(inputTypeName))
            {
                contextAttributes.SetAttribute("type", inputTypeName);  // Support restoration of type attribute, if any.
            }

            var expectedAttributes = new TagHelperAttributeList
            {
                { "class", "form-control radio-control" },
                { "value", value },
                { "type", inputTypeName ?? "radio" },       // Generator restores type attribute; adds "radio" if none.
            };
            var expectedPreContent  = "original pre-content";
            var expectedContent     = "original content";
            var expectedPostContent = "original post-content";
            var expectedTagName     = "not-input";

            var context = new TagHelperContext(
                allAttributes: contextAttributes,
                items: new Dictionary <object, object>(),
                uniqueId: "test");
            var originalAttributes = new TagHelperAttributeList
            {
                { "class", "form-control" },
            };
            var output = new TagHelperOutput(
                expectedTagName,
                originalAttributes,
                getChildContentAsync: (useCachedResult, encoder) =>
            {
                var tagHelperContent = new DefaultTagHelperContent();
                tagHelperContent.SetContent("Something");
                return(Task.FromResult <TagHelperContent>(tagHelperContent));
            })
            {
                TagMode = TagMode.StartTagOnly,
            };

            output.PreContent.SetContent(expectedPreContent);
            output.Content.SetContent(expectedContent);
            output.PostContent.SetContent(expectedPostContent);

            var htmlGenerator = new Mock <IHtmlGenerator>(MockBehavior.Strict);
            var tagHelper     = GetTagHelper(htmlGenerator.Object, model, nameof(Model.Text));

            tagHelper.InputTypeName = inputTypeName;
            tagHelper.Value         = value;

            var tagBuilder = new TagBuilder("input")
            {
                Attributes =
                {
                    { "class", "radio-control" },
                },
            };

            htmlGenerator
            .Setup(mock => mock.GenerateRadioButton(
                       tagHelper.ViewContext,
                       tagHelper.For.ModelExplorer,
                       tagHelper.For.Name,
                       value,
                       null,    // isChecked
                       null))   // htmlAttributes
            .Returns(tagBuilder)
            .Verifiable();

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

            // Assert
            htmlGenerator.Verify();

            Assert.Equal(TagMode.StartTagOnly, output.TagMode);
            Assert.Equal(expectedAttributes, output.Attributes);
            Assert.Equal(expectedPreContent, output.PreContent.GetContent());
            Assert.Equal(expectedContent, output.Content.GetContent());
            Assert.Equal(expectedPostContent, output.PostContent.GetContent());
            Assert.Equal(expectedTagName, output.TagName);
        }
示例#28
0
        public async Task ProcessAsync_CallsGenerateRadioButton_WithExpectedParameters(
            string inputTypeName,
            string model)
        {
            // Arrange
            var value = "match";            // Real generator would use this for comparison with For.Metadata.Model.
            var contextAttributes = new TagHelperAttributeList
            {
                { "class", "form-control" },
                { "value", value },
            };
            if (!string.IsNullOrEmpty(inputTypeName))
            {
                contextAttributes.SetAttribute("type", inputTypeName);  // Support restoration of type attribute, if any.
            }

            var expectedAttributes = new TagHelperAttributeList
            {
                { "class", "form-control radio-control" },
                { "value", value },
                { "type", inputTypeName ?? "radio" },       // Generator restores type attribute; adds "radio" if none.
            };
            var expectedPreContent = "original pre-content";
            var expectedContent = "original content";
            var expectedPostContent = "original post-content";
            var expectedTagName = "not-input";

            var context = new TagHelperContext(
                allAttributes: contextAttributes,
                items: new Dictionary<object, object>(),
                uniqueId: "test");
            var originalAttributes = new TagHelperAttributeList
            {
                { "class", "form-control" },
            };
            var output = new TagHelperOutput(
                expectedTagName,
                originalAttributes,
                getChildContentAsync: (useCachedResult, encoder) =>
                {
                    var tagHelperContent = new DefaultTagHelperContent();
                    tagHelperContent.SetContent("Something");
                    return Task.FromResult<TagHelperContent>(tagHelperContent);
                })
            {
                TagMode = TagMode.StartTagOnly,
            };
            output.PreContent.SetContent(expectedPreContent);
            output.Content.SetContent(expectedContent);
            output.PostContent.SetContent(expectedPostContent);

            var htmlGenerator = new Mock<IHtmlGenerator>(MockBehavior.Strict);
            var tagHelper = GetTagHelper(htmlGenerator.Object, model, nameof(Model.Text));
            tagHelper.InputTypeName = inputTypeName;
            tagHelper.Value = value;

            var tagBuilder = new TagBuilder("input")
            {
                Attributes =
                {
                    { "class", "radio-control" },
                },
            };
            htmlGenerator
                .Setup(mock => mock.GenerateRadioButton(
                    tagHelper.ViewContext,
                    tagHelper.For.ModelExplorer,
                    tagHelper.For.Name,
                    value,
                    null,       // isChecked
                    null))      // htmlAttributes
                .Returns(tagBuilder)
                .Verifiable();

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

            // Assert
            htmlGenerator.Verify();

            Assert.Equal(TagMode.StartTagOnly, output.TagMode);
            Assert.Equal(expectedAttributes, output.Attributes);
            Assert.Equal(expectedPreContent, output.PreContent.GetContent());
            Assert.Equal(expectedContent, output.Content.GetContent());
            Assert.Equal(expectedPostContent, output.PostContent.GetContent());
            Assert.Equal(expectedTagName, output.TagName);
        }
示例#29
0
        public async Task ProcessAsync_CallsGenerateTextBox_WithExpectedParameters(
            string inputTypeName,
            string model,
            string format)
        {
            // Arrange
            var contextAttributes = new TagHelperAttributeList
            {
                { "class", "form-control" },
            };

            if (!string.IsNullOrEmpty(inputTypeName))
            {
                contextAttributes.SetAttribute("type", inputTypeName);  // Support restoration of type attribute, if any.
            }

            var expectedAttributes = new TagHelperAttributeList
            {
                { "class", "form-control text-control" },
                { "type", inputTypeName ?? "text" },        // Generator restores type attribute; adds "text" if none.
            };
            var expectedPreContent  = "original pre-content";
            var expectedContent     = "original content";
            var expectedPostContent = "original post-content";
            var expectedTagName     = "not-input";

            var context = new TagHelperContext(
                tagName: "input",
                allAttributes: contextAttributes,
                items: new Dictionary <object, object>(),
                uniqueId: "test");
            var originalAttributes = new TagHelperAttributeList
            {
                { "class", "form-control" },
            };
            var output = new TagHelperOutput(
                expectedTagName,
                originalAttributes,
                getChildContentAsync: (useCachedResult, encoder) =>
            {
                var tagHelperContent = new DefaultTagHelperContent();
                tagHelperContent.SetContent("Something");
                return(Task.FromResult <TagHelperContent>(tagHelperContent));
            })
            {
                TagMode = TagMode.StartTagOnly,
            };

            output.PreContent.SetContent(expectedPreContent);
            output.Content.SetContent(expectedContent);
            output.PostContent.SetContent(expectedPostContent);

            var generator = new Mock <IDataSetHtmlGenerator>(MockBehavior.Strict);
            var dataSet   = DataSet <TestModel> .Create();

            dataSet.AddRow();
            dataSet._.Text[0] = model;
            var tagHelper = GetTagHelper(dataSet._.Text, generator: generator.Object);

            tagHelper.Format        = format;
            tagHelper.InputTypeName = inputTypeName;

            var tagBuilder = new TagBuilder("input")
            {
                Attributes =
                {
                    { "class", "text-control" },
                },
            };

            generator
            .Setup(mock => mock.GenerateTextBox(
                       tagHelper.ViewContext,
                       tagHelper.FullHtmlFieldName,
                       tagHelper.Column,
                       model,                                                             // value
                       format,
                       It.Is <Dictionary <string, object> >(m => m.ContainsKey("type")))) // htmlAttributes
            .Returns(tagBuilder)
            .Verifiable();

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

            // Assert
            generator.Verify();

            Assert.Equal(TagMode.StartTagOnly, output.TagMode);
            Assert.Equal(expectedAttributes, output.Attributes, CaseSensitiveTagHelperAttributeComparer.Default);
            Assert.Equal(expectedPreContent, output.PreContent.GetContent());
            Assert.Equal(expectedContent, output.Content.GetContent());
            Assert.Equal(expectedPostContent, output.PostContent.GetContent());
            Assert.Equal(expectedTagName, output.TagName);
        }