How to send html content through ajax request?

ByulTaeng picture ByulTaeng · Sep 18, 2010 · Viewed 12.7k times · Source

I have a form with a textarea (tinymce) for input content. When I perform an ajax request, I got the error:

A potentially dangerous Request.Form value was detected from the client

Then I've tried something like

html.encodeURIComponent() or escape() but the error is still here

HTML:

<form id="editForm" action="" method="post">
  <input type="text" id="title" name="title" />
  <textarea id="content" name="content"></textarea>
  <input type="button" id="submit" onclick="Submit();" />
</form>

Script (I use jQuery)

function Submit(){
 $.ajax({                
  url: 'ajax.aspx?type=addcontent&' + $('#editForm').serialize() + '&rnd=' + Math.random(),
  success: function(data) {
   alert('OK');
  }
 });
}

As soon as I press the submit button, the error appears. No ajax request is made. I've tried add ValidateRequest="false" to the aspx page but the problem is still here.

Any help is appreciated!

Answer

Darin Dimitrov picture Darin Dimitrov · Sep 18, 2010
$.post('/foo', { htmlContent: '<someHtml/>' }, function(result) {
    alert('ok');
});

Now the error comes from the server side script which doesn't accept HTML. The ASP.NET engine will automatically drop any requests containing HTML. There are different ways of disabling this behavior at your own risk. One of it consists of adding the ValidateRequest="false" to the aspx @Page header.

<%@ Page Language="C#" AutoEventWireup="false" ValidateRequest="false" %>

If it is an ASP.NET MVC application you could decorate the controller action to which you are posting with the [ValidateInput(false)] attribute:

[HttpPost]
[ValidateInput(false)]
public ActionResult Foo()
{
    ...    
}

It is also important to note that if you are running .NET 4.0 you will need to add the following to your web.config:

<httpRuntime requestValidationMode="2.0" />