I have an ajax control that returns user comments. Its served by a c# ajax handler page and the c# matches a timespan that a user can leave in the comments:
commmentToDisplay = Regex.Replace(c.CommentText, timeSpanRegex, "<a href=\'\' onclick=\'alert(\'Flash Required\');\'>" + actualTimeSpan + "</a>");
This produces the following json:
({
"numOfPages":"1",
"pageIndex":"1",
"comments": [
{
"user":"hmladmin",
"created":"29/03/2011 16:41:20",
"id":"1",
"comment":"<a href='' onclick='alert('Flash Required');'>00:00:21</a>",
"editable":"true",
"reportable":"true"
}
]
})
Confusingly when I look at the html in firebug it comes out as:
<a );="" required="" flash="" onclick="alert(" href="">00:00:21</a>
Ive tried:
commmentToDisplay = Regex.Replace(c.CommentText, timeSpanRegex, "<a href=\'\' onclick=\'alert(\"Flash Required\");\'>" + actualTimeSpan + "</a>");
and
commmentToDisplay = Regex.Replace(c.CommentText, timeSpanRegex, "" + actualTimeSpan + "");
And multiple permutations of I just cannot work out how to get the json and c# to return an anchor tag with an alert message in the onclick event.
Can someone help me to work out how I escape this properly so this problem doesnt happen.
The problem is when you create the string of HTML and has nothing to do with JSON:
"<a href=\'\' onclick=\'alert(\'Flash Required\');\'>" + actualTimeSpan + "</a>"
should probably be:
'' + actualTimeSpan + ''
You've got nested single quotes in 'alert('Flash Required');' which won't work. You need to change one set to double-quotes then escape them (\") for JSON. e.g. 'alert(\"Flash Required\");'
Related
I'm using PushSharp to handle push notifications for iOS.
Everything went well until I realized the way I'm handling the push isn't too powerful:
apnsBroker.QueueNotification(new ApnsNotification
{
DeviceToken = device.DeviceIdentifier,
Payload = JObject.Parse("{\"aps\":{\"alert\" : {\"title\" : \"" + title
+ "\", \"body\" : \"" + body + "\"}, \"badge\":" + badgeCount + "}, " +
"\"entity_id\" : \"" + entityId + "\", \"category_id\" : \"" + categoryId + "\", \"sub_id\" : \"" + subId
+ "\"}")
});
Edit / Update One of the parameters I am trying is \t\ud83d\uddbc️\ (basically I wanted to pass in the unicode character of the picture frame emoji, so it can be rendered in the APNS alert). It is breaking currently.
I am sending that in C# like this: #"\t\ud83d\uddbc️\"
So as you can see, I'm rendering out the JSON Payload and this framework takes in a JObject. The problem, as I immediately assumed during my code review, is that if any of those parameters above (title, body, etc) end up being strings such as { or " or { etc that it will "break" the JSON because JObject can't parse that as valid JSON.
What do you think I should do in this case? Do I have to encode it and I suppose the only drawback would be I have backslashes or something in the encoding? Any recommendations to permit the user input (title and body can be free form text so anything is possible).
Thank you in advance for any advice!
EDIT
Thank you again Zero for your help.
var escapedString = JsonConvert.ToString(normalString);
saved the day. It's important to note that if you are using this, then escapedString should not be wrapped in ""'s since it will already be escaped (as he mentioned below).
As long as your variables are quoted (inside ") there's no need to escape braces ({ and })
As for breaking the quote (having ") inside variables, you could do something like this:
//Escapes quotes
param = param.Replace(#"""", #"\""");
You also need to escape the escape char itself \
//Escapes backslash
param = param.Replace(#"\", #"\\");
Also, here are all valid escapes.
If you're using Newtonsoft.Json they have a method to do this for you.
Example usage below or take a look here. Be aware this will add quotes to the string for you.
//Or use the return value inline with interpolation "$" or concatenation "+"
var escapedString = JsonConvert.ToString(normalString);
I'm trying to replace a bunch of consecutive
var: $("#var").val()
lines in my JS script with a simple loop in c# like this:
#foreach(var q in myList){
#(q.var + ": $('#" + q.var + "').val()," + Environment.NewLine);
}
But any symbol I try to pass (', \" or "") generates the html entity (&-#39; or &-quot;).
var: $("#var").val()
and JS errors.
With a view only solution, is it possible to fix this?
To have an official answer in this post (or for futur readers) I will put my comment as an answer, which seems to have resolved the issue.
What you should use is Html.Raw to print raw content.
#(q.var + Html.Raw(": $(\"#") + q.var + Html.Raw("\").val(),") + Environment.NewLine);
I have the following code snippet, but I'm banging my head up against the wall trying to get the errors out of it.
I'm getting the following design time compile errors:
; expected
The name button does not exist in the current context.
Those same two messages also repeat for the DisplayReceipt.
Here is my code snippet being assigned in my code behind for html.
Can somebody please help me out?
Image_ID = "<input id='" + fuelticket.Image_ID + "' type="button" onclick='" + DisplayReceipt(fuelticket.Image_ID)"'>";
You just need to escape the quotes:
Image_ID = "<input id='" + fuelticket.Image_ID + "' type=\"button\" onclick='DisplayReceipt(" + fuelticket.Image_ID + ")'>";
Or use string.Format() to make things a bit cleaner:
Image_ID = string.Format("<input id='{0}' type=\"button\" onclick='DisplayReceipt({0})'>", fuelticket.Image_ID);
To make it work use the below code:
Image_ID = String.Format("<input id=\"{0}\" type=\"button\" onclick=\"{1}\">", fuelticket.Image_ID, DisplayReceipt(fuelticket.Image_ID));
The above looks more clear and optionally you can also use # for the string so you don't have to escape any special characters.
Image_ID = String.Format(#"<input id="{0}" type="button" onclick="DisplayReceipt({0})">", fuelticket.Image_ID));
If i have an image tooltip that is being populated from a database table. I am generating this html below from my server side C# code
public string GetImage()
{
return "<img class='iconSpace' title ='" + dataIssue + "' src='/Content/Images/Icons" + size + "/information_red.png' />";
}
the issue is that if the variable dataIssue has an apostrophe in it, it only shows the characters in the string up to that point.
What is the best way to show the whole string in the tooltip given the code above?
' is not special symbol for HTML, and browser shows whole string without problems, but you can have problems with following symbols " < > & they should be escaped as:
"
<
>
&
if your browser treats HTML standard incorrectly and cut the rest of the string, you can try to escape single quote with ' - this will work for all browsers
so, according HTML standard attribute values should be surrounded by " symbol, not by ', so the problem here should be solved:
dataIssue = any_kind_of_html_escape_function_here(dataIssue);
return "<img class=\"iconSpace\" title=\"" + dataIssue + "\" src=\"/Content/Images/Icons" + size + "/information_red.png\" />";
For asp.net htmlencode function is defined here: http://msdn.microsoft.com/en-us/library/w3te6wfz.aspx
Would this work for you?
string img = "<img class=\"iconSpac\" title=\"" + dataIssue + "\" " + "scr=\"/Content/Images/Icons\"" + size + "/information_red.png\" />";
You should use HttpUtility.HtmlEncode("...") for it.
http://msdn.microsoft.com/en-us/library/73z22y6h.aspx
How can I escape the Quotes so that this statement
string sScript =#"<script language='javascript'>function ShowDropDown(){var combo = $find("""+this.ClientID+""");combo.showDropDown(true);}</script>";
reads like this
function ShowDropDown() {
var combo = $find("ctl00_ctl00_MainContent_MainContent_VendorTypeIdComboBox");
combo.showDropDown(true);
}
EDIT- UPDATE
I might of asked the question wrong because i keep getting different errors. If I put the javascript directly on the page normally the function works. When I inject the javascript this way it doesnt work
I am doing this in code behind
string sScript =#"<script language='javascript'> function ShowDropDown(){ var combo = $find("""+this.ClientID+#"""); combo.showDropDown(true); } </script>";
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "autoopendropdown", sScript, false);
OnClientFocus = "ShowDropDown()";
it gets generated this way
<script language='javascript'> function ShowDropDown(){ var combo = $find("ctl00_ctl00_MainContent_MainContent_VendorTypeIdComboBox"); combo.showDropDown(true); } </script>
but the variable combo is null and thats what the problem is. I cant figure out why when it is registered with code-behind it doesnt work and when write it normally on the page it does.
Simple way: Add the same # at the beginning of the second string literal:
string sScript =#"<script language='javascript'>function ShowDropDown(){var combo = $find("""+this.ClientID+#""");combo.showDropDown(true);}</script>";
Better way: use string.Format
string sScript = string.Format(
#"<script language='javascript'>
function ShowDropDown(){
var combo = $find(""{0}"");combo.showDropDown(true);
}
</script>",
this.ClientID);
(Best way: separate concerns using unobtrusive javascript.)
string sScript = "<script language='javascript'>\n" +
"function ShowDropDown() {\n" +
" var combo = $find(""" + this.ClientID + """);\n" +
" combo.showDropDown(true);\n" +
"}\n" +
"</script>";
The escape for double quotes in C# (and most C family languages) is \"
Or you could just use single quotes since it's valid in JavaScript.
If I understand your question correctly, you want to concatenate this.ClientID with the rest of the script.
You can do this using the String.Format method like so:
string scriptFormat = #"<script language='javascript'>function ShowDropDown(){var combo = $find(""{0}"");combo.showDropDown(true);}</script>";
string sScript = String.Format(scriptFormat, this.ClientID);
Note that inside a verbatim string literal, "" produces a single " character.
You can escape them using the \ character.
For a complete list of escape combinations, see section 2.4.4.4 Character literals of the C# language specification.
NOTE: language is deprecated for script tags, use type
string sScript =#"
<script type='text/javascript'>
function ShowDropDown(){
var combo = $find(""" + this.ClientID + #""");
combo.showDropDown(true);
}
</script>";