Reputation: 2494
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><p>Hello World</p></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;
}
}
}
Upvotes: 1
Views: 359
Reputation: 432
When doing postback you will have ModelState filled.
@Html.TextAreaFor(x => x.Text)
tries to resolve this ModelState. It will resolve to encoded value, and encode it again (twice).
You could call ModelState.Clear()
in Post action before returning view
Upvotes: 1
Reputation: 2494
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.
Upvotes: 0