1

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.

animuson
  • 53,861
  • 28
  • 137
  • 147
Mark Ursino
  • 31,209
  • 11
  • 51
  • 83

2 Answers2

1

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

How do I escape a string inside JavaScript code inside an onClick handler?

Community
  • 1
  • 1
stun
  • 1,684
  • 3
  • 16
  • 25
  • 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 Jun 23 '10 at 15:49
  • 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 Jun 23 '10 at 15:56
0

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
  • 31,209
  • 11
  • 51
  • 83