Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ToolTip encoding issue

<asp:HyperLink ID="TestHyperLink" runat="server"></asp:HyperLink>

I am having the above hyperlink. I am just setting the text with below code:

string textFromUser = "This is test's.";
string encodedText=HttpUtility.HtmlEncode(textFromUser);
TestHyperLink.Text = encodedText;
TestHyperLink.ToolTip = encodedText;

The issue is that text of hyperlink is coming correct but tooltip is showing encoded characters. enter image description here

How can I make tooltip appear in the same way as text is?

like image 427
Rocky Singh Avatar asked Jan 17 '23 00:01

Rocky Singh


2 Answers

You're seeing that problem because the attribute value is being encoded twice.

  1. The ' character is encoded into &#39;;
  2. The & character is encoded into &amp;.

Finally the output is sent to the browser as title="This is test&amp;quot;s.". Since the attribute value is already being encoded by default, you can safely set the Tooltip property to the raw text and encode only the text for the Text property.

Note: In this case the attribute encoding is performed by default, but HtmlEncode in .NET versions before 4.0 did not encode the ' character. See HtmlEncode and UrlEncode Now Encode Single Quotation Marks.

Update: I did some googling and found out this interesting reference (Which ASP.NET Controls Automatically Encodes?) that may be outdated but at least for this specific case the documented behavior is the one you got.

like image 99
João Angelo Avatar answered Jan 21 '23 18:01

João Angelo


As mentioned the ToolTip property of a ASP.NET control will auto encode the value on output/rendering.

This means it is safe to set the tooltip to plain text as the page will sanitize the text on rendering.

Label1.ToolTip = "Some encoded text < Tag >"

Renders HTML output as:

<span title="Some encoded text &lt; Tag >"></span>

If you need to use text that is already encoded, you can set the title attribute instead:

Label1.Attributes("title") = "Some encoded text &lt; Tag &gt;"

Renders HTML output as:

<span title="Some encoded text &lt; Tag &gt;"></span>
like image 39
George Filippakos Avatar answered Jan 21 '23 18:01

George Filippakos