views:

40

answers:

2

I'm working in a Repeater over blog posts and I'm displaying a ShareThis JavaScript piece at the bottom. The Title and URL of the post are being sent to JS. In one test case, the title of a post has a single quote, e.g.

Mark's test post

Since I need to preserve that single quote when being sent to ShareThis, I need to wrap that JavaScript string in double quotes, however the string is being bound via a Literal and I cannot wrap the literal in double quotes:

This is want I want but DOES NOT WORK:

SHARETHIS.addEntry({ title: "<asp:Literal ID="ltlTitle" runat="server" />", etc..

I can only wrap the literal with single quotes like so:

SHARETHIS.addEntry({ title: '<asp:Literal ID="ltlTitle" runat="server" />', etc..

But that will result in bad front-end code:

SHARETHIS.addEntry({ title: 'Mark's test post', etc..

How can I encode this correctly or somehow wrap the control in double quotes? I'm aware of HttpUtility.HtmlEncode and Server.HtmlEncode but I don't see how those will help me.

Thanks in advance

+1  A: 

You need to "javascript-encode" your string on the server-side. You are probably looking for something like this.

http://stackoverflow.com/questions/97578/how-do-i-escape-a-string-inside-javascript-inside-an-onclick-handler

stun
I tried to do a replace in my C# on a single quote to the encoded value of `\x27` and it still renders incorrectly.
Mark Ursino
Since you are only worried about the single-quote, try this quick dirty fix.lblTitle.Text = title.Replace( "'", "\\'" );But if you want to be secure, eventually you'll need to create your own JavaScript encoding function.
stun
A: 

It turns out that I can actually use single quote in the ASP.NET control itself, which I never knew worked. I used to think that was a parser error but my page loads correctly

title: "<asp:Literal ID='ltlTitle' runat='server' />"

The result it what I want:

title: "Mark's test post"
Mark Ursino