Search code examples
jqueryajaxjsonasp.net-mvchtml-escape-characters

Action method is not called from $.ajax POST whenever the sent text contains "<"


I'm using the following to display some text on my intranet site:

@Html.TextAreaFor(model => model.Text)

Now the text may contain some XML-like formatting, which seems to present a problem when I try the following on form submit:

$("form").on("submit", function () {
  var model = $(this).serialize();
  $.ajax({
    url: "/Test/Foo",
    type: "POST",
    data: model,
    dataType: "json",
    success: doSomething(response)
  });
  return false;
});

The action method takes a POCO which serves as the model of the site with the form I'm submitting and returns some JsonResult.

As long as the text in the <textarea> is "normal" text, there is no problem and I enter the action method correctly and my POCO has the correct property values. But once I enter the text <foo> (with the braces) into the <textarea>, my action method isn't hit anymore.

I tried using $(this).serializeArray() instead and it doesn't work either. The serialize() and serializeArray() methods even replace the "<" and ">" signs (and also "="; first I thought that this was causing the problem), so I guess they're internally using escape(), but nothing is sent.

When I manually send as data

{
  Text: escape($("#myTextArea").val()),
  Description: $("#someInput").val(),
  Id: $("input[type=hidden]").val()
}

it works, that is, I enter my action method, but of course I have a weirdly formatted string to work with on the server.

What exactly is the problem here? Some encoding issue? Do I have to serialize in some other way to circumvent this problem?


Solution

  • This is a security feature of ASP.Net MVC. By default when it detects HTML in a received value it will prevent execution in case it is part of an XSS attack.

    To disable this feature on an Action you need to use the ValidateInput attribute and set it to false. Try this:

    [ValidateInput(false)]
    public ActionResult Foo(Model myModel) 
    {
        // your logic here...
    }
    

    You can also disable this on a model property level by using the AllowHtml attribute:

    public class MyModel {
        public Guid Id { get; set; }
    
        [AllowHtml]
        public String Description { get; set; }
    }