Net Core: How to create CSS with TagBuilder?

问题: How do I use Tag Builder CSS Class? I want to incorporate this in a style class img { max-width: 100%; max-height: 100%; padding: 0px; background-color:white; } TagBui...

问题:

How do I use Tag Builder CSS Class?

I want to incorporate this in a style class

img {
max-width: 100%;
max-height: 100%;
padding: 0px;
background-color:white;
}

TagBuilder image = new TagBuilder("img");

How would I then add the attributes?


回答1:

So I'm just going to demonstrate an example for this here. I am not using the styles or the context provided, just doing a sample in two different ways. In the example provided here, I have two custom tags.enter image description here

And I am add the following style rules.

<style>
    .black-div {
        height:40px;
        width: 40px;
        background-color: black;
    }
</style>

These are the two tag helpers that correspond to the tags provided previously.

[HtmlTargetElement("div-with-class")]
public class ClassTagHelper : TagHelper
{
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.TagName = "div";
        output.Attributes.SetAttribute("class", "black-div");
    }
}
[HtmlTargetElement("div-with-style")]
public class StyleTagHelper : TagHelper
{
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.TagName = "div";
        output.Attributes.SetAttribute("style", "height:40px;width: 40px;background-color: black;");
    }
}

Hope this Helps!


回答2:

You could put all your css styles in a css class in your root css file.

<style>
.myImage {
    max-width: 100%;
    max-height: 100%;
    padding: 0px;
    background-color: white;
}
</style>

The use below code to add the css class:

TagBuilder builder = new TagBuilder("img");
builder.AddCssClass("myImage");
builder.MergeAttribute("src", url);
builder.MergeAttribute("alt", "AltImage");
  • 发表于 2019-07-07 21:00
  • 阅读 ( 208 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除