Search code examples
javascriptjqueryajaxasp.net-mvc-4jqte

Ajax call not working when trying to send html markup to server


I am using jquery text editor plugin for creating a html mark up. I take the markup created by the text editor in a js variable and post that variable to server using ajax call.

Mark up in cshtml:

<div>
   <div id="textEditor">@Html.Raw(Model.htmlMarkUp)</div>
</div>
<input type="button" value="Save" onclick="SaveChanges();" />

JS:

$(document).ready(function () {
    $('#textEditor').jqte();
});

    function SaveChanges(){
    var txtContent = $(".jqte_editor").html();//.jqte_editor is the div added by plugin


        var path = '/Pages/saveChanges';
        $.ajax({
            type: "POST",
            url: path,
            data: { htmlMarkUp: txtContent },
            success: function (result) { alert(result) },
            error: function () { }
        });
    }

Model:

public class MyModel
{
  public string htmlMarkUp{ get; set; }
}

Controller:

public string saveChanges(MyModel oModel)
{
 ....
}

Problem:

The action result is called correctly unless I don't use any of the beautifier tool provided in plugin i.e. if I wrote a simple plain text in text editor the ajax call work correctly but as soon as if I use any of the tool like bold tool the ajax call stops working.

Firstly I thought this is due to the limitation of json size in web config, but that is not also a problem.

For specifying json size I wrote as following in web.config:

<system.web.extensions>
  <scripting>
      <webServices>
        <jsonSerialization maxJsonLength="5000">
        </jsonSerialization>
      </webServices>
  </scripting>
</system.web.extensions>

The problem has nothing to do with the markup size. The problem is when, when I use any tool like bold italic of the text editor plugin.

What is going wrong

Thanks in advance.


Solution

  • I got the problem. The problem was not with the text editor but with the asp security. Whenever I was trying to send html content (containing html tags) to my server via ajax the server was rejecting such request.

    When I was not using any text editor tool it was considered as plain string, but as soon as I used any tool like bold tool, the variable also where I am collecting the text editor markup has also got html tags. Such parameter when reached to server was rejected by server due to security issue.

    So to skip this security check I add following attribute to my action result:

    [ValidateInput(false)]
    public string saveChanges(MyModel oModel)
    {
     ....
    }
    

    This is the server side solution. You can also handle the issue at client side by encoding the variable to base64 encoding:

    var txtContent = $(".jqte_editor").html();
    
    var encodedHtml =  $.base64.encode(txtContent );