I'm currently using a custom control to display text on a page and then allow administrators to edit this text via a pop-up dialog at the same point. The dialog that administrators then use allows HTML input so that the text can be formatted however the administrator would like. When this is then submitted, I'm getting the standard error of:
A potentially dangerous Request.Form value was detected from the client
(ctl00$body$UITextElement1$txtEditor="<h2>Example</h2>")
I know that I can get around this by disabling the request validation, but as I'm using this as a control that I would like to be able to place across the website, I wouldn't really like to disable this validation across the board.
I've attempted to get around this by adding this to the control:
<asp:Panel ID="UITextEditor" runat="server">
<div runat="server" ID="panelcontent">
<textarea runat="server" id="txtEditor" class="ckeditor"></textarea>
</div>
<div id="panelfooter">
<asp:Button ID="CancelButton" runat="server" Text="Cancel" />
<asp:Button ID="SaveButton" runat="server" Text="Save" CommandName="SaveUIText" OnClick="SaveButton_Click" OnClientClick='<%# string.Format("encode(\"{0}\", \"{1}\")", this.txtEditor.Name, this.txtEditor.ClientID) %>' />
</div>
</asp:Panel>
Along with this JavaScript method to remove the offending characters:
function encode(txtId, formId) {
var tb = document.getElementById(formId);
if (tb != null) {
tb.value = tb.value.replace(/</g, '<');
tb.value = tb.value.replace(/>/g, '>');
// Try changing the form data as well
// in case this is being passed by unmodified
var form = document.forms[0];
if (form != null) {
form.elements[txtId].value = tb.value;
}
}
}
However, even with this, the error is still coming up. The JavaScript method is running, and is modifying the value of the textarea and the form data, but when the submit goes ahead, the error still displays the original text. I have checked the SaveButton_Click
method as well, but the exception is being raised before this even starts to run.
I have also tried replacing the <
with &l;
and >
with &g;
in case it was to do with my replacement, but that hasn't helped either.
Any ideas on what I could do to get around this issue without disabling the request validation?
Edit: It seems that one of the issues was that I didn't realise that due to me using CKEditor (which I didn't believe would affect this), I needed to access the text in a different way.
Rather than the method above, I had to change this to the following to get the text out of the control correctly:
var tb = CKEDITOR.instances[formId];
if (tb != null) {
var newText = tb.getData();
The same goes for updating the text afterwards, this needed to be one with tb.setData(newText);