Search code examples
c#javascriptasp.nethtml-encode

Wrap an ASP.NET control with double quotes


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.


Solution

  • 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"