Search code examples
javascriptasp.net-mvcckeditorwysiwygckeditor4.x

CK Editor altering content on postback (4.10.1)


I'm having an issue with CKEditor encoding it's html content when the model state is not valid. For example if I submit "Hello World" it hits the server successfully as an encoded html string <p>Hello World</p>.

If I want to load content I pass a decoded html string as the value to the textarea and it loads fine <p>Hello World</p>. However if the page posts back, e.g when (!ModelState.IsValid) then it renders incorrectly as:

<p>&lt;p&gt;Hello World&lt;/p&gt;</p>

Here's the kicker, it still receives <p>Hello World</p> as the field value on the postback. What gives?

I'm using the following source:

const ckEditorSrc = "//cdn.ckeditor.com/4.10.1/standard/ckeditor.js";

and the bellow initialiser:

CKEDITOR.replace('js-ck-editor', { htmlEncodeOutput: true});
CKEDITOR.config.height = 600;

I've checked and the initializer is hit after postback.

The only other bit of information that may help is that the source is loaded dynamically using a simple loadScript function.

function loadScript(url, callback) {// loads a script onto a page
    var script = document.createElement("script");
    script.type = "text/javascript";
    if (script.readyState) {  //IE
        script.onreadystatechange = function () {
            if (script.readyState === "loaded" || script.readyState === "complete") {
                script.onreadystatechange = null;
                callback();
            }
        };
    } else {  //Others
        script.onload = function () {
            callback();
        };
    }

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}

Here's the full init function for brevity:

var ckEditor = function () {// init ckeditor

    if ($('#js-ck-editor').length) {
        const ckEditorSrc = "//cdn.ckeditor.com/4.10.1/standard/ckeditor.js";
        loadScript(ckEditorSrc, function () {

            CKEDITOR.replace('js-ck-editor', { htmlEncodeOutput: true});
            CKEDITOR.config.height = 600;
        }
    }
}

Solution

  • So it turns out the issue was with using asp.net html helpers.

    I changed @Html.TextAreaFor(m=>m.Text)

    to <textarea name="Text" id="js-ck-editor">@Model.Text</textarea>

    Now it works fine. After hours of scrolling ckeditor documentation it turns out it was such a simple solution. Ah well hope this helps someone else one day.