Monday, March 7, 2011

Escaping single quote in server side script in asp page

We had a javascript function that was using server side property like the following,

<a href="#" onclick="MyFunction('<%=SomeProperty %>')">Link</a>

When "SomeProperty" contains single quote "'" this was causing script errors in the page.




To solve this error, just add the following after SomeProperty

.ToString().Replace("'","\\'").Replace("\"","&quot;")

so that it will look like this at the end

<a href="#" onclick="MyFunction('<%=SomeProperty.ToString().Replace("'","\\'").Replace("\"","&quot;") %>')">Link</a>

This will solve the problem


Note: when i tried to do this from the code behind, replacing the quote, it didn't working

No comments:

Post a Comment