jerrythomas38
jerrythomas38

Reputation: 769

Net Core: Is it Possible to Merge TagBuilder Style Attributes with CSS Files?

Is it possible to merge style attributes from a Tagbuilder with style attributes coming from CSS/SCSS Files? It seems like Tag builder is totally removing my attributes in SCSS files. In example below, its only following width from Tag builder and ignoring my other CSS files background color.

test.MergeAttribute(
  "style", "width: " + CarouselWidth + @"px;  
  height:" + CarouselWidth + "px; height: 100%;"
);

.test {
  background-color:green
}

Upvotes: 0

Views: 1346

Answers (1)

David Liang
David Liang

Reputation: 21476

TagBuilder is here to help you build a HTML element a little bit easily without having to concatenate strings. Should you understand you're building an element from scratch. That means if you don't merge an attribute called "background-color" into the tag builder, it won't have an attribute called "background-color".

The following code should also set the attribute "background-color":

using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Razor.TagHelpers;

namespace DL.SO.Framework.Mvc.TagHelpers
{
    public class TestTagHelper : TagHelper
    {
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            int carouselWidth = 300;

            TagBuilder div = new TagBuilder("div");

            div.MergeAttribute(
                "style", 
                $"width: { carouselWidth }px; height: { carouselWidth }px; background-color: green;");

            output.Content.SetHtmlContent(div);
        }
    }
}

enter image description here


Because your post is unclear, based on your "code", I think you should set the attribute class as well so that your style could be applied.

int carouselWidth = 300;

TagBuilder div = new TagBuilder("div");

div.MergeAttribute(
    "style", 
    $"width: { carouselWidth }px; height: { carouselWidth }px;");

div.MergeAttribute(
    "class", 
    "test");

enter image description here

Upvotes: 1

Related Questions