Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net 4.0 is encoding single quote when using Attributes.Add

.Net 4.0 is encoding single quotes when I am using Attributes.Add to add client side events to my asp.net objects. In the previous versions this didn't happen.

for example :

<asp:Image runat="server" ID="imgTest" ImageUrl="~/DateControl/cal.gif" />

 imgTest.Attributes.Add("onmouseover", "alert('Hello')");

When I view the client side output, I am getting

 <img id="ctl00_MainContent_calFromTimeStamp1_imgTest" onmouseover="alert(&#39;Hello&#39;)" src="../DateControl/cal.gif" style="border-width:0px;" />

I found a workaround by creating a custom encoder : creating custom encoding routines but I don't want to stop the encoding for the whole website just because of this issue. Anybody got a workaround or an idea of how to fix this?

like image 405
Hassan Mokdad Avatar asked Aug 06 '13 09:08

Hassan Mokdad


2 Answers

According to Microsoft you should not be adding JavaScript to HTML attributes using WebControl.Attributes.Add(), exactly because it will encode the attribute value:

You cannot add client-side script to a WebControl instance using the Attributes collection. To add client-side script, use the ClientScript property on the Page control.

Source

The advice is to use the Page.ClientScript.RegisterExpandoAttribute(string controlId, string attributeName, string attributeValue, bool encode) method. In your case it would look like this:

Page.ClientScript.RegisterExpandoAttribute(
  imgTest.ClientID, 
  "onmouseover", 
  "alert('Hello')", 
  false /* Do not encode */
);

This will result in a piece of JavaScript in your page that sets the attribute client-side.

like image 103
Michiel van Oosterhout Avatar answered Nov 15 '22 13:11

Michiel van Oosterhout


The best way to set event attributes in .NET is to call a single function :

imgTest.Attributes("message") = "Hello";
imgTest.Attributes("onmouseover") = "showMessage(this);"

And on your page, or registered script :

function showMessage(ctrl) 
{
  alert(ctrl.getAttribute('message'));
}
like image 29
Sebris87 Avatar answered Nov 15 '22 11:11

Sebris87