I'm running into an error when I try put this is in a textbox like this,
tbGameTitle.Text = "<iframe id = 'ForIframe' src='http://e.gamesalad.com/play/117208' allowTransparency='true' scrolling='no'></iframe>";
when I click on my button
myThing.InnerHtml = tbGameTitle.Text;
it throws this error
A potentially dangerous Request.Form value was detected from the client (tbGameTitle="<iframe id = 'ForIfr...").
If I have this load on the pageload event then its fine. But as soon as I enter this in the textbox and click on my button, it throws that error. I had it working in another project from way back and it never threw this error.
ASP.Net form content is checked for dangerous content when it is submitted (things like HTML and javascript are flagged as being potentially dangerous and are rejected). There are a few ways of allowing this content to be submitted, HTML encoding your text before it is send to the server or disabling request validation using a tag in the top of your page (potentially unsafe!):
<# Page validateRequest="false" %>
More information on request validation can be found at this link
You need to escape characters like "<".
Read a little about: XSS
This post must be helpful.
the main code you want from that page is:
// The event to escape the data and store in our HiddenField
jQuery('.allow_html textarea').blur(function () {
jQuery(jQuery(this).parent()).find('input[type="hidden"]').val(escape(jQuery(this).val()));
});
// The code to unescape the code and set it in our textbox
jQuery('.allow_html textarea').each(function(idx, item) {
var value = jQuery(jQuery(item).parent()).find('input[type="hidden"]').val();
jQuery(item).val(unescape(value));
});
that will escape HTML code in the input.
and, at the server side you need to unescape it:
// encode the data
HtmlCodeHiddenField.Value = Uri.EscapeDataString(EscapedHtml);
// decode the data
string myHtml = Uri.UnescapeDataString(HtmlCodeHiddenField.Value);
Related
I have RadioButtonList, in which I am adding images dynamically:
this.RlCredtiCardTypes.Items.Add(new ListItem(String.Format("<img src='{0}'>", GetImageUrl(item.Code), item.Code)));
This will render fine, but on post back I get the following error:
A potentially dangerous Request.Form value was detected from the client
I understand the error. The question is; how do I dynamical add images to my RadioButtonList without causing this error?
I have also tried to HttpContext.Current.Server.HtmlEncode the img string, but that renders the literal text and not the image.
As a note, I do not want to set EnableEventValidation="false", as this will leave my page open to nefarious activity.
This question seems to related to this question, but its not marked as answered.
message A potentially dangerous Request.Form value was detected from the client comes whenever you try to pass html string via post in asp.net
Your best way to do is encode string into base64 and than decode it while showing into form and while posting form's data back just convert all html related data into base64 string via jquery or javascript.
The reason this occurs is the html code for the image is being sent across in the post back. You can disable validation on the RadioButtonList by adding ValidateRequestMode="Disabled" validaterequestmode(v=vs.110)
<asp:RadioButtonList ID="RlCredtiCardTypes" runat="server" ValidateRequestMode="Disabled"></asp:RadioButtonList>
This will leave the rest of your form securely checking against evil code.
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 have encountered an unexpected behaviour and/or bug in the .net postback system.
I have a page that uses a master page to provide common elements, with form inputs split between the child and master pages. The form submit button is located on the master page, and I am attempting to process postback on the masterpage.
Any time I attempt to submit data where the form contains any non empty values and the url contains parameters, the page fails to process correctly. This does not occur if the page is submitted under either condition by itself.
The form postback method is post.
The page fails to load and in firefox returns the no element found error.
I have checked for correct class names ect and I do have empty attributes in non form elements, but as the page loads correctly at first I don't think that is relevant. I have also checked for infinately looping code.
This is the current postback handling code:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
save_page();
}
page_render();
}
//save
private void save_page()
{
dev_text.Text = "save in progress";
}
Setting text in an HTML element on the server will only be seen on the browser when the HTML is sent to the browser. Normally this happens once the entire processing of the page has completed... so normally quite some time after the user initiated the post-back.
Instead of setting the text on the server, consider setting the text directly on the browser at the moment of submission. Something like...
function setSavingText(){
// Vanilla javascript...
document.getElementById("<%=dev_text.ClientId%>").innerHTML = "save in progress";
// JQuery...
$("#<%=dev_text.ClientId%>").text("save in progress");
}
<asp:Button runat="server" ... OnClientClick="setSavingText();" />
The above function contains both a line for vanilla (normal) javascript, and one for the jQuery library. You only need one of them.
I have made an application in javascript using HTML fields in asp.net, as asp text boxes were disturbing the ids, so i used html fields, which are working fine with javascript, now i want to fetch database table columns on page load, and want to assign to html fields, what is the best way to do so? Help me!!!!
You could go back to using the ASP TextBoxes and access the ids in JavaScript as follows:
<%= IDofTextBox.ClientID %>
It's probably the easiest as naturally they can then be accessed in the code behind very easily.
you can use asp text boxes fine if you grab a reference in your javascript to their asp.net generated ID via <%= textboxname.ClientId %>
This is not the right way to do it (I wouldn't recommending it), but if its what you need, then it will work.
Add method="post" action="<your path here>" to your form element and when the submit button posts, you will be able to access all the form variables like so:
string txtName = Request["TextBox1"] ?? string.Empty; //replace textbox 1 with text box name
Just be sure to replace the action in form to your page etc..
But really, going back to <asp:TextBox... will save you a lot more time and as Ian suggested, you can access them with javascript by the server tags <%= TextBox1.ClientId %>
ps: also, the ?? is a null coalesce character. its a short form of saying
if(Request["textbox1"] != null)
txtName = Request["textbox1"];
else
txtName = "";
If I understand you correctly. You just need to add runat="server" and id="someName" to the html fields and access them in the code behind by its given id.
I have an aspx web page (opener) which opens a popup window
In the popup window I need to retrieve the value of a hidden field which exists in the opener page.
So this is all straight forward using Javascript.
However, here’s the problem, I need the value of the hidden field to be processed SERVER side before the pop up page loads
(Basically, the hidden field contains XML which need to be deserialized server side and the data used to construct the DOM of the popup page)
So how do I pass the data in the hidden field of the opener, to get processed serverside in popup?
The data is Waaay too long to be passed as a GET. i.e. in the querystring of the popup page
What are the other options here?
Retrieve it using Javascript in popup, then do a postback to reload the page (very ugly)
Somehow post the data when opening the popup? Is this possible and can I stil pass other info via the querystring
Any other ideas?
Have a form like this
<form method="POST" action="action.php" onsubmit="open_popup(this);">
<input name="really-big-field" type="hidden">
</form>
also, javascript like this
function open_popup(form)
{
window.open('action.php', 'actionpopup','width=400,height=300');
form.target = 'actionpopup';
}
window.open() will open a popup like you want.
Setting the form's target to the opened popup will make sure that the form will POST to that popup.
Since a POST is made, you can send larger data than you can send using GET.
You can process the data server side in action.php (or in ASP.Net/VB file).
My usual solution to this sort of issue is to use XmlHTTPRequest to post the XML to the server, which simply stores the XML against some unique ID such as a GUID and have the ID returned from the server.
The URL you provide for your popup would then only need to carry this ID rather than the whole XML. Now when the server code on the other end of that URL needs the XML it can use the ID to look up the XML (probably deleting it from its temporary store at the same time) and can process the XML as if had been posted in the request.
Edit: Sorry, I realize this doesn't answer your question. I didn't read it clearly enough and didn't realize you needed to do it server side. I suppose if you wanted to take this path, though, you could then AJAX up your page to build it.
Parent page:
foo = 'bar';
child = open ("popup.html");
// you can now access the new windows functions with child.varname and child.function()
Child page:
alert(window.opener.foo);
Should alert Foo. Therefore you can:
somevar = window.opener.document.getElementById('id').value;
to get the field's value.