Ajax call not working when trying to send & return raw html

253 views Asked by At

I am using Ajax call to invoke C# method that is processing user paste input by removing unwanted html tags and attributes.

When I paste in content with html formatting (tags & attributes), my Ajax call doesn't work. Can you please advise how Ajax parameters should be defined for such scenario (send raw html to server side code and get raw html returned)?

view:

@(Html.Kendo().Editor()
 .Name("myEditor")
 .PasteCleanup(p => p.Custom("myPasteCleanUp")
)

script:

function myPasteCleanUp(input) {
      var response = null;
      if (input != null) {
       $.ajax({
         type: "POST",
         url: '/Home/htmlTagCleanUp',
         data: { userInput: input },
         async: false,
         success: function (response) {
            input = response;
         },
       });
     }
    return input;
   }

controller:

[HttpPost]
[AllowAnonymous]
public ActionResult htmlTagCleanUp(string userInput)
{
  userInput = userInput;
  return Content(userInput, "text/html");
}
4

There are 4 answers

0
Tom S On

It turned out the missing part was sanitizing HTML:

var  = document.createElement('div');
element.innerText = html;
var sanitizedHTML = element.innerHTML;
1
Abinesh Amatya On

The thing that is preventing your AJAX call is because you have added if conditions:

if (html != null) {
}

Can you tell me where the html variable is defined. Nonetheless, I think you are trying to check the input null values and if we replace the html by input variable on the if the condition it should work:

if (input != null) {
}
0
pushkar singh On

I guess the issue is that MVC considers data with tags as a bad request.

Therefore would suggest you try it above the action method in your controller:

[ValidateInput(false)]
0
Manthan Makani On

Looks like you need to add the [ValidateInput(false)] attribute to your method as it may treat as an XSS attack.

Ref: ValidateInput(false) vs AllowHtml