简体   繁体   中英

Unable to combine tags using TagBuilder

I'm trying to build a combination tag:

First tag: <span class="requiredInidicator">* </span> Second tag: <label>SomeText</label> (Attributes snipped for brevity)

I would like to combine these to return an MVCHtmlString but the following code ignores the span completely. Could someone point out what I am doing wrong

Here is my code:

// Create the Label
var tagBuilder = new TagBuilder("label");
tagBuilder.Attributes.Add("id", "required" + id);
//I get the id earlier fyi - not pertinent fyi for this question )

// Create the Span
var required = new TagBuilder("span");
required.AddCssClass("requiredInidicator"); 
required.SetInnerText("* ");

//Now combine the span's content with the label tag
tagBuilder.InnerHtml += required.ToString(TagRenderMode.Normal);
tagBuilder.SetInnerText(labelText);
var tag = MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.Normal));
return tag;

When the tag is created, the span is ignored completely. When I inspect the tag during debug, it doesn't care about the required that I appended via .InnerHtml+=

Is there something obvious I am doing wrong?

Try like this:

var label = new TagBuilder("label");
label.Attributes.Add("id", "required" + id);
//I get the id earlier fyi - not pertinent fyi for this question )

// Create the Span
var span = new TagBuilder("span");
span.AddCssClass("requiredInidicator");
span.SetInnerText("* ");

//Now combine the span's content with the label tag
label.InnerHtml = span.ToString(TagRenderMode.Normal) + htmlHelper.Encode(labelText);
return MvcHtmlString.Create(label.ToString(TagRenderMode.Normal));

You shouldn't be calling SetInnertext (especially after having just assigned Innerhtml ). You want to use one or the other.

if you're looking to append, keep going with InnerHtml += labeltext .

You could always do:

string output = "";
output += tabBuilder.ToString(TagRenderMode.Normal);
output += required.ToString(TagRenderMode.Normal);

return MvcHtmlString.Create(output);

The issue could be the TagBuilder assumes one root level HTML tag, but I'm not sure about that.

这个怎么样:

tagBuilder.SetInnerText(labelText + required.ToString(TagRenderMode.Normal));

try using the InneHtml property on the span

// Create the Span
var required = new TagBuilder("span");
required.InnerHtml ("SOME TEXT");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM