开发者

Wrap an ASP.NET control with double quotes

开发者 https://www.devze.com 2023-01-04 23:33 出处:网络
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

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.


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?


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号