Hello and thank you in advance. I am generating controls from C# code behind and want to apply an onclick attribute that will sent a modal to block display. When the code executes, apostrophes in the onclick function string are encoded to ' and I want to stop that from happening and pass the raw text.
I have tried the following to solve the problem with no resolution:
\'
''
<%= myString %>
HtmlString(myString).ToHtmlString();
There are probably other iteration that i tried but I lost track of them all.
This is the code section creating the control:
HtmlGenericControl viewMoreInfo = new HtmlGenericControl("span");
//HtmlString onclick1 = new HtmlString($"document.getElementById('{i.il_itemcode}Modal').style.display = 'block'");
string onclick1 = $"document.getElementById('{i.il_itemcode}Modal').style.display = 'block'";
viewMoreInfo.Attributes["onclick"] = onclick1;
viewMoreInfo.Attributes["class"] = "w3-bar-item w3-button w3-white w3-xlarge w3-right";
viewMoreInfo.InnerText = "+";
Here is an example of what it renders as:
<span onclick="document.getElementById('TEST1Modal').style.display = 'block'" class="w3-bar-item w3-button w3-white w3-xlarge w3-right">+</span>
I need the apostrophe to render correctly for the function to work.
Any help would be greatly appropriated.
Your question is misleading because "I need the apostrophe to render correctly for the function to work." is incorrect. Note the following which is an exact copy of your example, and the click event works just fine as it currently being rendered.
<p id="TEST1Modal" style="display:none">This is hidden until clicked</p>
<span onclick="document.getElementById('TEST1Modal').style.display = 'block'" class="w3-bar-item w3-button w3-white w3-xlarge w3-right">+</span>
Related
I'm trying to encode data that is to be displayed on a separate page (.aspx) after a user submits a form with their information and questions. There are both text input and textarea fields that the user can fill out.
I'm using the <%#: %> expression to place this data on the page since it does the HTML encoding, but have run into an issue with the encoding also encoding the br tags as text instead of actual line breaks.
Is there a way to make it so that the br tags still cause a line break, but leave everything else encoded using this method?
Example of user input:
Hi
This is what should be responded with.
Here is an example of the code that places it on the page:
<p><%#: ((DiscussionThread.Discussion)Container.DataItem).Text %></p>
What it currently displays on the page:
Hi<br /><br />This is what should be responded with.
Thanks in advanced!
Don't know, will it help you in your case or no, but I always use next way:
string forInput = yourTextBoxID.Text.ToString().Replace(Environment.NewLine, "%NL%");
string forOutput = forInput.Replace("%NL%", Environment.NewLine);
If in forOutput Environment.NewLine will not work, change it to <br />
%NL% it is just a identificator, u may change to anything else.
I have a textfield which displays a string which contains < and >. The code throws an error because of that. How can I allow the usage of those chars in my textfield?
Thanks :)
Problem is that when this gets posted to server, it will not work, doesn't matter what you try. This is the ASP.NET XSS protection, which can be disabled like so:
<%# Page ... ValidateRequest="false" %>
Trouble is, you'll have to be very careful validating all the postback yourself. Easier way is to escape all the contents of textbox using javascript just before posting. You can escape it using same HTML escaping, then unescape in server side code.
Update:
Example of escaping. This will flash the changed text on screen before postback - ideal solution is to use a hidden field for this, i.e. assign value to a hidden field, instead of that same field. This is the simplest version:
<script>
function EscapeField(){
document.getElementById("your client control ID").value =
escape(document.getElementById("your client control ID").value);
}
</script>
And in code-behind:
this.ClientScript.RegisterOnSubmitStatement(this.GetType(),
"EscapeField", "EscapeField();")
Update:
Again, warning - if you save HTML in your database like this, and then just display it to the client, you are directly vulnerable to XSS attacks. There are worms out there that will find and exploit your web site. Make sure you cleanse the HTML you are getting.
If you're in an asp.net page, you can wrap the whole of the output text in a
Server.HtmlEncode("YourTextWith<and>Characters")
function and it will encode any dodgy characters for you.
If, for some reason, you're doing this in a .cs file, you can use System.Web.HttpUtility.HtmlEncode("YourTextWith<and>Characters")
before passing it to the presentation layer.
Convert them to < and >. In Html, < is converted to < and > is converted to > without it thinking it's part of the markup. So the string <Blah> will be <Blah>.
Edit: I forgot, to automatically convert them and escape all HTML characters (so this isn't an issue for other things), in Asp.net you can use Server.HtmlEncode(string) to automatically convert all characters that could cause issues to their HTML equivalent.
The easiest solution is to disable request validation in single pages
<%# Page ... ValidateRequest="false" %>
but don't forget to enable requestValidationMode="2.0"
<system.web>
...
<httpRuntime requestValidationMode="2.0" />
</system.web>
This solution could espose some threats.
Another smart solution is to replace via javascript text written by user to make it safe for validation: <tag> is considere dangerous, but < tag> is considered safe!
A javascript replacement can solve the problem.
function validateTxt() {
$("textarea, input[type='text']").change(function () {
html = $(this).val(); //get the value
//.replace("a" , "b") works only on first occurrence of "a"
html = html.replace(/< /g, "<"); //before: if there's space after < remove
html = html.replace(/</g, "< "); // add space after <
$(this).val(html); //set new value
});
}
$(document).ready(function () {
validateTxt();
});
<asp:TextBox ID="TextBox1" runat="server"><</asp:TextBox>
I don't know if your question is related to this or if you are getting a validateRequest issue
You can either use the TextBox.Text property which will HTML-encode whatever you enter
<asp:TextBox ID="TextBox1" runat="server" Text="<>"></asp:TextBox>
or you can enter the html names for < and >.
<asp:TextBox ID="TextBox1" runat="server"><</asp:TextBox>
or you can enter the html codes
<asp:TextBox ID="TextBox1" runat="server"><</asp:TextBox>
for the name and code conversions, check out this chart.
your problem is,you cannot use html tags in .net controls. so set the ValidateRequest="false" in your aspx page and encode the text before you saving the text.
//encode
private string Encode(string text)
{
byte[] encodedText = System.Text.Encoding.UTF8.GetBytes(text);
return System.Convert.ToBase64String(encodedText);
}
when you retrieving your text make sure to decode the encoded text.
// Decode:
private string Decode(string encodedText)
{
byte[] decodedText = System.Convert.FromBase64String(encodedText);
return System.Text.Encoding.UTF8.GetString(decodedText );
}
I am facing a problem I have to fill a TextArea programatically. I used the following code.
System.Windows.Forms.HtmlElement reviewText = myDoc.GetElementById("review-text");
reviewText.InnerText = Program.mainForm.richTextBox1.Text.Trim();
This works fine and it sets the text in TextArea control. The problem that I am facing is that this text appears light gary. When the user clicks over this text it disappears. It happens only on first click.
So I tried the following code to first click this box and then set the text.
reviewText.InvokeMember("click");
And then tried to set the text in the TextArea but got the same behaviour.
I dug into the source of the page and found some script associated with this TextArea.
Source of TextArea
<textarea onkeyup="javascript:yelp.ui.widget.countChars(this.form.comment,5000);" onkeydown="javascript:yelp.ui.widget.countChars(this.form.comment,5000);" name="comment" id="review-text" class="form400" rows="8" cols="40" style="height: 86px;"></textarea>
Script associated with TextArea
<script type="text/javascript">
var bizName = "Geary Club";
if ($('review-text'))
{
new yelp.ui.widget.DefaultValueTextField($('review-text'), 'Please write here');
}
Will somebody suggest to me how to insert the text into this TextArea control?
Is this an ASP.NET web app? If it is, the System.Windows.Forms.HtmlElement is a problem. What I think is going on is that you need to somehow disable the new yelp.ui.widget.DefaultValueTextField JavaScript code when you're pre-filling the TextArea. Are you able to use an ASP.NET TextBox control with the multi-line properties set? If so, I'd use that and change your top code to just set the .Text property of the Textbox control.
Either way, in the Javascript (if this is jQuery), I'd do this:
if ($('review-text') && $('review-text').val() != "")
{
new yelp.ui.widget.DefaultValueTextField($('review-text'), 'Please write here');
}
That way the default value is only set if there is no text.
I changed the HTML of text area.And remove the class="form400 default_valued_text_field" attribute from its html.
myDoc = this.webBrowser1.Document;
myDoc.GetElementById("review-text").OuterHtml = "<textarea id=\"review-text\" onkeyup=\"javascript:ui.widget.countChars(this.form.comment,5000);\" onkeydown=\"javascript:ui.widget.countChars(this.form.comment,5000);\" name=\"comment\" rows=\"8\" cols=\"40\" style=\"height: 86px;\"></textarea>";
After that i set the inner text of this element
myDoc.GetElementById("review-text").InnerText = "Testing";
I'm very new to ASP.net. I have a c# content page, in which I want to inset this code half way down within the HTML:
<%
HttpResponse r = Response;
r.Write(HttpContext.Current.Request.ServerVariables["SERVER_NAME"]);
%>
But when I view the page, this content comes out first, before even the tag.
Any ideas on how to get this code inline instead?
Thanks!
EDIT
I'd just like to add a note to all who answered this question to explain what you've done.
You spared your valuable time to help me, a stranger to you, solve a difficult problem at work, which allowed me to get out of the office on Friday night, just in time to catch the last bus to my home 50 miles away, and see my wife who was sick in bed. You didn't just answer my question, you made my day SO much better. THANK YOU so much!
Steven
Because you are doing a Response Write, that will push out before everything else. If you want to just imbed something at a specific point you can do:
<%= HttpContext.Current.Request.ServerVariables["SERVER_NAME"]) %>
This <%= %> will write any string to that exact location in the HTML.
You could also use a Literal control and assign its Text property in your codebehind or use a Label if you require formatting.
You can put a label on the page where you want the text to appear and then set the label's text instead of doing like this. Simply put an asp label on the page and frmo your code behind do
myLabel.Text = HttpContext.Current.Request.ServerVariables["SERVER_NAME"].ToString();
where myLabel is the ID of your label in your HTML Markup.
Define a DIV on the page like this, where you want the outputted string to be displayed:
<div id="myDIV" runat="server" />
Then, instead of r.Write() you can simply set the inner text of the DIV to be what you want:
myDIV.innerText = HttpContext.Current.Request.ServerVariables["SERVER_NAME"];
when you use Response.Write("..."); its shows up before page header , instead of using Response.Write you can put a label on the form wherever you want to see the message and set label's Text property.
Or if you just want the text, with no html markup.
Use a literal.
In aspx file
<asp:Literal ID="MyLiteral" runat="server" />
in code-behind
MyLiteral.Text = HttpContext.Current.Request.ServerVariables["SERVER_NAME"].ToString();
I have an ASP.NET web application and at a certain point I do this:
mycontrol.stringparameterforjscript = "document.getElementById('" + myotherparam + "').value = 'Hello'";
The problem is that this thing does not work.
As you can see this sets a javascript in some event of some tag. Well when the page is redered the problem is that my parameter look like this:
<textarea onfocus="document.getElementById('myvalue').value = 'Hello'"></textarea>
I must precise that this textbox I'm trying to set is located inside a InsertItemTemplate of a ListView and it is not so easy to intialize. For this reason I inserted my initialization code that you see inside the load event handler of my textbox. I can say you one thing: If this code referred to a text box located freely in the page and I called this piece of code from the load event handler of the page, this would work well. But I do not know how to do in this particular case.
I'm also considering the possibility to create a webcntrol to handle such a problem. I don't really know what's the best practice in this case.
I think you might need the # on both string literals in your assignment, and remove the slashes:
mycontrol.stringparameterforjscript = #"document.getElementById('" + myotherparam + #"').value = 'Hello'";
EDIT
How I did it:
On the .aspx:
<asp:Textbox ID="tbTest" runat="server" TextMode="MultiLine" />
In the code:
protected void Page_Load(object sender, EventArgs e)
{
string myotherparam = "paramval";
tbTest.Attributes.Add("onfocus", #"document.getElementById('" + myotherparam + #"').value = 'Hello'");
}
Resultant output:
<textarea name="tbTest" rows="2" cols="20" id="tbTest" onfocus="document.getElementById('paramval').value = 'Hello'"></textarea>
OK, I finally managed it. HTML Encoded strings recognized by the javascript engine, how's it possible?
As you will see there is nothing to worry about in what happens.