A couple of years ago I posted my solution for the infamous “A potentially dangerous Request.Form value was detected from the client” error when using TinyMCE with ASP.NET 4.0.

The solution worked (mostly) without turning off request validation.

Since then, I’ve changed my approach slightly; I’ve dropped the Moxiecode TinyMCE ASP.NET assembly and have gone with a purely JavaScript solution. I think it works better, and it’s a lot cleaner and more up to date.

There are a few parts to this:

  1. Implementing TinyMCE JavaScript version
  2. Decoding HTML server-side on POST
  3. Handling TinyMCE re-encoding HTML on Postback

Implementing TinyMCE JavaScript version

Download TinyMCE (just grab the main package, which “contains all you need for production usage”), extract and copy the files into your solution.

Any page that has a TinyMCE text editor will need to include the base js file and a chunk of initialization script to set up all our options.

<script type="text/javascript" src="/_assets/tiny_mce/tiny_mce.js"></script>

<script type="text/javascript" >
    tinyMCE.init({
        mode: "specific_textareas",
        editor_selector: "tinymce",
        encoding: "xml",
        convert_urls: false,
        theme: "advanced",
        plugins: "spellchecker,pagebreak,style,layer,table,advhr,advimage,advlink,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,paste,directionality,fullscreen,visualchars,nonbreaking,xhtmlxtras",
        extended_valid_elements: "iframe[src|width|height|name|align]",
        theme_advanced_buttons1: "spellchecker,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect,|,print,fullscreen",
        theme_advanced_buttons2: "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
        theme_advanced_buttons3: "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,media,advhr,|",
        theme_advanced_toolbar_location: "top",
        theme_advanced_toolbar_align: "left",
        theme_advanced_path_location: "bottom",
        theme_advanced_resizing: true,
        theme_advanced_resize_horizontal: false,
        theme_advanced_styles: "Link to Image: lightbox;Image Right Border: rightbordered;Image Left Border: leftbordered;Darker Text: darker",
        setup: function (ed) {
            ed.onSaveContent.add(function (i, o) {
                o.content = o.content.replace(/&#39/g, "&apos");
            });
        }
    });
</script>

I’ve got all my site-specific configuration in the plugins and themes options; you’ll probably want to change those for your implementation.

There are three key areas here you want to pay attention to.

mode: "specific_textareas",
editor_selector: "tinymce",

These two tell TinyMCE to only initialize textareas with a class attribute containing “tinymce”. That means we won’t accidentally create TinyMCE instances if we’re using other textareas on the page.

encoding: "xml",

The encoding option (off by default) tells TinyMCE to XML-encode all HTML in our textarea on POST. This is critical for ASP.NET.

setup: function (ed) {
    ed.onSaveContent.add(function (i, o) {
        o.content = o.content.replace(/&#39/g, "&apos");
    });
}

Apostrophes will give you a lot of grief unless you explicitly add this onSaveContent() handler to convert them to a safe, encoded string. This is critical for ASP.NET.

Now all we have to do is include a textarea with the right class, and the init() function will take care of setting up TinyMCE for us.

<textarea
    id="htmlBody"
    runat="server"
    class="tinymce"
    rows="40"
    cols="120" />

Easy!

Decode HTML server-side on POST

Because TinyMCE is encoding HTML, we might choose to decode it server-side before storing it in the database. If you don’t decode TinyMCE output now, you’ll need to decode it before rendering anywhere.

public String SystemText
{
    get
    {
        return HttpUtility.HtmlDecode(bodyHtml.Value);
    }
    set
    {
        bodyHtml.Value = value;
    }
}

In codebehind (or wherever else you’re referring to your textarea in code), use HttpUtility to decode TinyMCE’s output when retrieving the value of the textarea for storage.

Handling TinyMCE re-encoding HTML on Postback

TinyMCE is set to encoding=xml, which encodes everything in the textarea on POST. That leads to a bunch of nasty &amp; &gt; etc. instead of real HTML when the page reloads after a Postback.

So, on Postback, we decode the textbox so TinyMCE is starting "clean". Here’s what sample codebehind could look like to do this:

protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack)
    {
        if (bodyHtml != null && !string.IsNullOrWhiteSpace(bodyHtml.Value))
        {
            bodyHtml.Value = HttpUtility.HtmlDecode(bodyHtml.Value);
        }
    }
}

I’m very happy with this method; it works great using ASP.NET 4.0 and its more robust page validation model.

More importantly, I don’t have that nasty feeling I’m doing something terrible by setting ValidateRequest="false” in the page declaration!

posted on Monday, May 21, 2012 5:43 PM | Filed Under [ Development Microsoft ]

Comments

Gravatar
# re: ASP.NET 4.0, TinyMCE and “A potentially dangerous Request.Form value was detected” (Scott @ 6/5/2012 2:51 AM)

Awesome! Simple and works great!

I just started using Tiny_mce and this was one of those major issues to solve. Next is to get the file and image mangers to work :-)
 
Gravatar
# re: ASP.NET 4.0, TinyMCE and “A potentially dangerous Request.Form value was detected” (Bryan @ 6/23/2012 3:22 AM)

How can you get this to work when the asp:TextBox is in a FormView?

Thanks.
 
Gravatar
# re: ASP.NET 4.0, TinyMCE and “A potentially dangerous Request.Form value was detected” (Sam Wood @ 6/23/2012 8:20 AM)

Hey Bryan,

As long as the TextBox is being rendered as a textarea (which I believe is just TextMode="MultiLine"), and has the same CssClass as the script's editor_selector ("tinymce" in this case), the init script should add the TinyMCE controls as normal.

Where your approach will differ is in locating and re-decoding the contents of each TextBox. You'll most likely need to use FindControl against the FormView on the server-side during postback to find and re-decode the TextBoxes.

There's a lot more literature on the web about using FindControl with ListView, but it'll be basically the same process.
 
Gravatar
# re: ASP.NET 4.0, TinyMCE and “A potentially dangerous Request.Form value was detected” (David Wainwright @ 8/4/2012 2:16 AM)

This is great - thanks a lot, I mop my furrowed brow to you!
 
Gravatar
# re: ASP.NET 4.0, TinyMCE and “A potentially dangerous Request.Form value was detected” (Boogle @ 8/7/2012 9:28 AM)

Excellent article. Professional and very very useful, it cuts out switching off request validation, which is VERy important!

Well done.
 
Gravatar
# re: ASP.NET 4.0, TinyMCE and “A potentially dangerous Request.Form value was detected” (Mehul Mehta @ 9/22/2012 2:39 AM)

Thank you.
Its very very use full.
It save my lots of time.
Thanks again :)
 
Gravatar
# re: ASP.NET 4.0, TinyMCE and “A potentially dangerous Request.Form value was detected” (Saerluvla Arul @ 11/8/2012 9:10 PM)

You done a great job!
Thank you so much!
 
Gravatar
# re: ASP.NET 4.0, TinyMCE and “A potentially dangerous Request.Form value was detected” (saerluvlaArul @ 11/8/2012 10:29 PM)

You done a great job.
Thank you so much.
 
Gravatar
# re: ASP.NET 4.0, TinyMCE and “A potentially dangerous Request.Form value was detected” (Jeff @ 11/28/2012 11:16 AM)

Thank's heaps. Just implemented tinyMCE in an asp.net app. Was getting the request form error. Implemented this fix with no effort.

This is quite late, but as to Bryan's question. In the codebehind change Value to Text because it is an asp.net text box. So, bodyHtml.Value = HttpUtility.HtmlDecode(bodyHtml.Value); now look's like bodyHtml.Text = HttpUtility.HtmlDecode(bodyHtml.Text);
 
Gravatar
# re: ASP.NET 4.0, TinyMCE and “A potentially dangerous Request.Form value was detected” (Steve @ 11/29/2012 5:42 AM)

Best article on this subject, by far. Really sums it up nicely. In fact, one of the better articles on any programming issue I've read recently.
 
Gravatar
# re: ASP.NET 4.0, TinyMCE and “A potentially dangerous Request.Form value was detected” (Pravin @ 12/6/2012 9:26 AM)

Thanks a lot. It was very useful.
 
Gravatar
# re: ASP.NET 4.0, TinyMCE and “A potentially dangerous Request.Form value was detected” (Shodhan Shetty @ 2/4/2013 10:34 PM)

Great solution. But path may not be same as you mentioned. I searched for reflected schema folder in C:/
 
Gravatar
# re: ASP.NET 4.0, TinyMCE and “A potentially dangerous Request.Form value was detected” (Greg @ 3/22/2013 6:51 AM)

Awesome explanation ! Just the touchy spots I needed to handle. Thanks a ton.
 
Gravatar
# re: ASP.NET 4.0, TinyMCE and “A potentially dangerous Request.Form value was detected” (Adi @ 7/23/2013 1:41 AM)

this solution doesn't work anymore, still "A potentially dangerous Request.Form value was detected from the client " error...
 
Gravatar
# re: ASP.NET 4.0, TinyMCE and “A potentially dangerous Request.Form value was detected” (David @ 7/30/2013 6:40 AM)

4.0.* has changed so now you should use this instead.

setup: function (editor) {
editor.on('SaveContent', function (ed) {
ed.content = ed.content.replace(/&#39/g, "&apos");
});
}
 
Gravatar
# re: ASP.NET 4.0, TinyMCE and “A potentially dangerous Request.Form value was detected” (Sunil @ 8/20/2013 11:51 PM)

TypeError: ed.onSaveContent is undefined
[Break On This Error]

ed.onSaveContent.add(function (i, o) {
 
Gravatar
# re: ASP.NET 4.0, TinyMCE and “A potentially dangerous Request.Form value was detected” (MarekLani @ 9/12/2013 6:43 AM)

Hi nice post thanks, but unfortunetely I am using tinyMce 4 and the setup part is not working for me, it gives error, can you help me somehow please? Thank you.
 
Gravatar
# re: ASP.NET 4.0, TinyMCE and “A potentially dangerous Request.Form value was detected” (terroare @ 9/17/2013 11:13 PM)

Real life saver.
Thanks!
 
Gravatar
# re: ASP.NET 4.0, TinyMCE and “A potentially dangerous Request.Form value was detected” (Rohit singh @ 11/28/2013 4:51 PM)

4.0.* has changed so now you should use this instead.

setup: function (editor) {
editor.on('SaveContent', function (ed) {
ed.content = ed.content.replace(/&#39/g, "&apos");
});
}

This worked for me after a full day of searching for the single quote issue in tinymce. Thanks a LOTTTTTTTTTTT! :)
 
Gravatar
# re: ASP.NET 4.0, TinyMCE and “A potentially dangerous Request.Form value was detected” (ziv_t @ 4/8/2014 11:49 PM)

thx
works great
 
Gravatar
# re: ASP.NET 4.0, TinyMCE and “A potentially dangerous Request.Form value was detected” (mf @ 2/1/2015 6:40 AM)

Not sure how it works!
I need this as my asp.net application used ValidRequest="false" for the time being.
Great if anyone sends me a working demo. Please help me.
Thanks a lot in advance.
 
Gravatar
# re: ASP.NET 4.0, TinyMCE and “A potentially dangerous Request.Form value was detected” (mf @ 2/2/2015 6:21 PM)

I have problem understanding the above method.
I need it for my asp.net application too like “A potentially dangerous Request.Form ..."
Please help me. Thanks.
 
Gravatar
# re: ASP.NET 4.0, TinyMCE and “A potentially dangerous Request.Form value was detected” (Connie @ 3/6/2015 1:19 PM)

Does not work. Object doesn't support property or method 'on'

How do I get this to work in MVC5 with Razor view?

Post Comment

Title *
Name *
Email
Url
Comment *  
Remember me
Please add 3 and 8 and type the answer here:

Search

Site Sections

Recent Posts

Archives

Post Categories

WHS Add-In Tutorial

WHS Blogs

WHS Development