Reputation: 953
While using ASP.NET controls, for example
<h1 id="header" runat="server">text</h1>
if we want to change the text of the header we can do it probably by two properties InnerHTML
and InnerText
. I want to know what is the basic difference between the two properties?
Upvotes: 9
Views: 20860
Reputation: 732
InnerHtml
lets you enter HTML code directly, InnerText
formats everything you put in there for it to be taken as plain text.
For example, if you were to enter this in both properties: Hello <b>world</b>
This is what you would get with InnerHTML:
Hello world
That is, exactly the same HTML you entered.
Instead, if you use InnerText
, you get this:
Hello <b>world</b>
And the resulting HTML would be Hello <b>world</b>
Upvotes: 16
Reputation: 54359
When in doubt, go to the source (or decompile):
In HtmlContainerControl
:
public virtual string InnerText
{
get
{
return HttpUtility.HtmlDecode(this.InnerHtml);
}
set
{
this.InnerHtml = HttpUtility.HtmlEncode(value);
}
}
public virtual string InnerHtml
{
get
{
if (base.IsLiteralContent())
{
return ((LiteralControl)this.Controls[0]).Text;
}
if (this.HasControls() && this.Controls.Count == 1 && this.Controls[0] is DataBoundLiteralControl)
{
return ((DataBoundLiteralControl)this.Controls[0]).Text;
}
if (this.Controls.Count == 0)
{
return string.Empty;
}
throw new HttpException(SR.GetString("Inner_Content_not_literal", new object[]
{
this.ID
}));
}
set
{
this.Controls.Clear();
this.Controls.Add(new LiteralControl(value));
this.ViewState["innerhtml"] = value;
}
}
Both properties ultimately use InnerHtml
, but setting InnerText
HTML encodes the value so that it will be displayed literally in the browser versus interpreted as markup.
Remember that assigning to InnerHtml
will not encode the value, and thus any user-driven content should be sanitized prior to assignment.
This also emphasizes how important it is to be mindful of view state (note the last line of InnerHtml
's setter; everything ends up in view state whether or not you need it).
Upvotes: 2
Reputation: 1206
InnerHtml allows to insert html formated text within an HTML container, while InnerText only allows plain text (if I remember correctly this property trims any type of html you try to put in it)
Upvotes: 0