Search code examples
c#htmlhtmlgenericcontrol

Dynamically generating span element inside paragraph element


I am trying to add HTML Generic Controls with a span & paragraph placed inside a div and then inside a placeholder - dynamically.

Here's what the HTML shoud look like inside the placeholder:

<div class="card">
    <p class="icon_bar card-img-top"><span class="fa app_icon fa-cogs"></span>My header text goes here.</p>
    <div class="card-body">
        <h5 class="card-title">My H5 Title Text</h5>
    </div>
</div>

I can't seem to get the span element to show up and the text after the span element before the closing paragraph tag. Here's what I've tried:

//No issues here
System.Web.UI.WebControls.PlaceHolder ph = new System.Web.UI.WebControls.PlaceHolder();
int phaddone = cardID;
ph.ID = "PlaceHolder" + phaddone.ToString();
CardDiv.Controls.Add(ph);

//This seems to work fine too
HtmlGenericControl oustideDiv = new HtmlGenericControl("div");
oustideDiv.ID = "cardDiv" + cardID.ToString();
oustideDiv.Attributes.Add("class", "card");

//Here's the problem
var p1 = new HtmlGenericControl("p");            
p1.Attributes.Add("class", "icon_bar card-img-top");            

var s1 = new HtmlGenericControl("span");
s1.Attributes.Add("class", "fa app_icon fa-cogs");

p1.Controls.Add(s1);
p1.InnerHtml = headerText;
oustideDiv.Controls.Add(p1);

//This works too
HtmlGenericControl bodyDiv = new HtmlGenericControl("div");
bodyDiv.Attributes.Add("class", "card-body");

var h1 = new HtmlGenericControl("h5");
h1.InnerHtml = titleText;
h1.Attributes.Add("class", "card-title");
bodyDiv.Controls.Add(h1);


ph.Controls.Add(oustideDiv);

Solution

  • You need to change this code as you are overwriting the span

    p1.Controls.Add(s1);           //add the span
    p1.InnerHtml = headerText;    //but then overwrite the span with 'headerText' !
    oustideDiv.Controls.Add(p1);
    

    to

    p1.Controls.Add(s1);
    p1.InnerHtml = @"<span class=""fa app_icon fa-cogs"" />" + headerText;
    oustideDiv.Controls.Add(p1);