问题
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?
回答1:
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));
回答2:
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
.
回答3:
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.
回答4:
How about this:
tagBuilder.SetInnerText(labelText + required.ToString(TagRenderMode.Normal));
回答5:
try using the InneHtml property on the span
// Create the Span
var required = new TagBuilder("span");
required.InnerHtml ("SOME TEXT");
来源:https://stackoverflow.com/questions/13746776/unable-to-combine-tags-using-tagbuilder