ASP.NET MVC TagBuilder.SetInnerText () does not set text correctly
So I am creating an extension method HtmlHelper and I am facing a problem when using TagBuilder.SetInnerText (). The helper displays the option tag. Here is the source of the helper:
public static string Option(this HtmlHelper helper, string value, string text, object htmlAttributes) {
TagBuilder tagBuilder = new TagBuilder("option");
tagBuilder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
tagBuilder.MergeAttribute("value", value);
tagBuilder.SetInnerText(text);
return tagBuilder.ToString(TagRenderMode.SelfClosing);
}
In my mind, I call
<%= Html.Option("value", "text", new { }) %>
but the inner tag text is not set and I am left with
<option value="value"> </option>
Any ideas on why SetInnerText () is not setting the text correctly?
Thank.
+2
Tim Banks
source
to share
2 answers
return tagBuilder.ToString(TagRenderMode.SelfClosing) - is the problem
It tries to deduce <option value="" />
where there is nowhere to insert the InnerText.
Do it:
return tagBuilder.ToString(TagRenderMode.Normal)
+8
user151323
source
to share
I think the correct way to use InnerText
this is below. You need to set InnerText
in Create Tag and after defining additional attributes.
TagBuilder tagBuilder = new TagBuilder("select")
{
InnerHtml = "set Anything"
};
tagBuilder.MergeAttribute("value", value);
0
Rodrigo zimmermann
source
to share