Wrap an ASP.NET control with double quotes - c#

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"

Related

escape sequence while assigning style class to div in a label

I came across a text assignment to a label in c# code. The code is
lbltext.text = string.format("<div class=\"test\">{0}</div>", "succesfully updated").
I'm using Label control and documentations says:
The Text property can include HTML. If it does, the HTML will be passed unchanged to the browser, where is might be interpreted as markup and not as text.
Even after reading it I don't understand what it is the purpose of using escape after "class=".
Is it like assigning the css class "test" to that div element?
If yes then why can't we do it like 'class="test"'?
Unable to find any answers googling. Can someone please clarify?.
So I'm not 100% sure what this question is asking, but if it really is as simple as "why not just use class="test", then that would be because double quotes are used to describe literal strings. So What you would end up with would be
"<div class=" test ">{0}</div>"
Which would cause a build error for starts. The escaping is done to allow double quotes to be used in a string without terminating the string early.
Worth noting that for classes, you can also you single quotes to get around this.
"<div class='test'>{0}</div>"
For Example :)

Why isn't font rendered in HTML when surronded by "

I have some HTML stored in a database and I am generating an static HTML file out of it. However when i open the file in the browser, the font doesn't render as I expect it.
I have tracked down the problem and I see it is because of & quot;
<p><span style="font-family: "Roboto Regular";">Some text</span></p>
Now if I replace the & quot; with double quotes, it works fine.
This is also generated through C#. What is the best approach to fix this?
Should I just use Replace function to convert them to quotes or is there a library that I can use to do it more efficiently? or is it even simpler to fix.
Thanks for your thoughts.
You can use System.Web.HttpUtility.HtmlDecode (and Encode) to handle this sort of thing.
However you should be asking yourself why your font string includes HTML encoded characters.
HTML is spewed out as is and not parsed until it reaches the browser. This is a security measure to ensure that no malicious code can be run in the browser. I will recommend you use the Replace function you suggest. If you want to take security to the next level, I will suggest you encode the opening and closing braces of HTML tags and including that inside your Replace method.
I will explain why...
<p><span style="font-family: "Roboto Regular";">Some text</span></p>
Since you said c#, your code clearly shows that HtmlDecode doesn't decode quotes for font-family. This is caused by copy-paste html to database while using HtmlEncode as below.
HtmlEncode("<p><span style="font-family: "Roboto Regular";">Some text</span></p>");
As you notice above usage of quote in another quote is illegal in html unless it is escaped. That is why HtmlDecode thinks this is escaped quote and leaves it as it is.
SOLUTION: You can replace the font-family quotes with single quote before HtmlEncode but this would create SQL issue to address which is replacing single quote with double single quotes. Off course you need to reverse it after HtmlDecode. HtmlEncoding again or replacing with double quotes would not fix the issue since you are creating another illegal quotes in quotes. That is why you need to simply replace [&quote;] with single quote ['] and you can do this in frontend.
("<p><span style="font-family: "Roboto Regular";">Some text</span></p>").replace(""", "'");

how to replace single quote with string in javascript

I have some data from a lookup like this: =winz\ach'dull.
How can I replace single quotes (') with ("").
This is my code =>
<input type="button" id="btnSelect" onclick="Select('<%#Eval("LoginName").ToString().Replace("'", "\'")%>');" value="Select"/>
I'm trying to create code like this:
Select('<%#Eval("LoginName").ToString().Replace("'", "\'")%>');
but it does not not work.
Please correct and help me. Thanks.
In pure javascript we could do :
var a="winz\ach'dull.";
alert(a.replace("'",'"'));
And that would replace your single quote.
Note: Your code is C# not javascript.
You can escape quotes with the "\" character and it works perfectly with HTML. So the answer to exactly what you wrote would be: (this is just to humour you in the future)
"Select('<%#Eval(\"LoginName\").ToString().Replace(\"'\", \"\'\")%>');"
But you have syntax errors in what you are writing and that Eval stuff is not javascript so I don't know why ToString and Replace are attached to it. I've changed it a little based on guessing what you're trying to do:
<input onclick="Select('<%#Eval("LoginName")%>').ToString().Replace(\"'\", \"'\");">
Note that if you're using C# or something on the server side it doesn't need to be escaped because by the time the HTML is parsed in the DOM, typically a browser the source no longer contains your server side code and only the output!

using a string format with parameters to set onclick

Why doesn't this work?
<input type="button" id="btnAccept" value="Accept" onclick='<%# String.Format("accept('{0}','{1}','{2}','{3}-{4}');", Container.DataItem("PositionID"), Container.DataItem("ApplicantID"), Container.DataItem("FullName"), Container.DataItem("DepartmentName"), Container.DataItem("PositionTitle"))%>' />
The onclick doesn't do anything.
Your best bet is to look at the generated HTML. I think it's a really good habit to check the generated HTML in text format and how it renders on-screen, all the time. Besides errors such as this (which can easily be spotted in the generated HTML), it will help you catch other possible invalid uses of HTML which may render as intended in one browser while rendering terribly in another. HTML rendering engines employ many tricks to try and make invalid HTML look okay.
Anyway, all things aside (such as, assuming accept(...) exists, and all other calls in the tag are correct) I think the issue you are having is as follows:
onclick='<%# String.Format("accept('{0}','{1}','{2}','{3}-{4}');", ... )%>'
This line is probably going to evaluate to look something like this:
onclick='accept('{0}','{1}','{2}','{3}-{4}');'
With all single quotes, all the onclick attribute will see is onclick='accept(' which is not a valid javascript method call. You're going to want to use the "" strings, which you can embed in the format string by escaping them.
String.Format("accept(\"{0}\",\"{1}\",\"{2}\",\"{3}-{4}\");", ... )
Then, you should be able to get the correct combination of ' and " within the attribute:
onclick='accept("{0}","{1}","{2}","{3}-{4}");'

C# HtmlEncode, then Javascript insert using .innerHTML

What follows is a piece of text that gets HtmlEncoded in C# before being sent to the browser (during a callback). Once received, in Javascript I do myDiv.innerHTML = theStringBelow;
<span xmlns:asp="http://schemas.microsoft.com/ASPNET/20"
xmlns:SharePoint="Microsoft.Sharepoint.WebControls"
xmlns:ext="my_namespace:my_xslt_extension">Some text to be shown.</span>
However, what results is that I simply see the exact text shown above. It isn't being treated as an html element that got added to the DOM, but as plain text. When I add the exact same text through javascript (e.g., I skip the callback, and just say myDiv="exactString") it DOES get added correctly (it gets treated as a span).
What is going on? Do I have to un-encode it? Should I not have encoded to begin with?
Edit
The question still stands for curiosity's sake, but I have fixed the issue simply by not HtmlEncoding the data. An earlier issue must have added onto this one, making me think the HtmlEncoding was still necessary.
You should not HTMLEncode it if it is to become HTML nodes. What HTML encoding will do is turn your string from above into this:
<span xmlns:asp="http://schemas.microsoft.com/ASPNET/20"
xmlns:SharePoint="Microsoft.Sharepoint.WebControls"
xmlns:ext="my_namespace:my_xslt_extension">Some text to be shown.</span>
Try passing the string in as it is. You will of course have to escape the string. But once it has become a string in JavaScript it should be unescaped as it is being made into a string in memory. Then you should be able to do the div.innerHTML call and get your expected result. The escaping of the string can probably be accomplished by doing the following:
// in your .cs code-behind/view/whatever.
string = string.replace("""", "\""");
Which should produce:
<span xmlns:asp=\"http://schemas.microsoft.com/ASPNET/20\"
xmlns:SharePoint=\"Microsoft.Sharepoint.WebControls\"
xmlns:ext=\"my_namespace:my_xslt_extension\">Some text to be shown.</span>
Which you can then output like so:
// in your webform/view
<script type="text/javascript">
var mystring;
mystring = "<%=string;%>";
</script>
Let me know how that works out for you.
HTML Encode will turn < into < and so on. This breaks HTML Formatting and is used so blocks of text like this:
Insert <name> here
Does not turn out like this:
Insert here
If your intent is to have the <span ... get inserted into the html directly you either need to NOT encode it on the way out, or if that will disrupt transmission, you need to decode it in js before you set the .innerHTML part.

Categories