Everything works perfectly with create/edit pages, where CKEditor encodes input and server side returns decoded for CKEditor to display. All that goes out of the window when validation error occurs making page reload after it hit the server.
Even though I am decoding on return to the view, CKEditor won't properly render html tags. If I do Html.Raw for the same field, I can see its showing html properly, so its no the issue with decoding. For the life of me I can't figure out why this case is any different from editing ( loading existing html into CKEditor from dB) which works perfectly. But on page reload it all goes out of whack.
Things I've tried, decoding, encoding, neither. Adding delay to CKEditor initialization.
Server side return code.
if (!ModelState.IsValid)
{
q..Text = System.Net.WebUtility.HtmlDecode(q.Text);
return View(q);
}
View
<div class="form-group">
@Html.LabelFor(model => model.Text, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextAreaFor(model => model.Text, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Question.Text, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Text, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.Raw(Model.Text)
</div>
</div>
JavaScript for CKEditor
var ckEditorInstance;
$(document).ready(function () {
CKEDITOR.replace('Text', { htmlEncodeOutput: true, enterMode: CKEDITOR.ENTER_BR });
ckEditorInstance = CKEDITOR.instances.Text;
ckEditorInstance.on('instanceReady', function () { UpdateTextArea(); });
ckEditorInstance.on('change', function () { UpdateTextArea(); });
});
function UpdateTextArea() {
ckEditorInstance.updateElement();
};
</script>
Using CKEditor v4.8.0 • 13-12-2017
Image to show the issue, below CKEditor @Html.Raw(Model.Text)
output, showing that html is decoded properly.
Resolved this by using @Html.Raw(Model.Text)
Instead of TextAreaFor
With @Html.HiddenFor(model=>Model.Text)
To preserve data when posting to server/controller And Javascript to update hidden field and encode html
<script type="text/javascript">
var ckEditorInstance;
$(document).ready(function () {
CKEDITOR.replace('ckEditorRaw', { enterMode: CKEDITOR.ENTER_BR });
ckEditorInstance = CKEDITOR.instances.ckEditorRaw;
ckEditorInstance.on('instanceReady', function () { UpdateTextArea(); });
ckEditorInstance.on('change', function () { UpdateTextArea(); });
});
function UpdateTextArea() {
ckEditorInstance.updateElement();
//Set hidden field and escape html
$("#Question_Text").val(new Option((ckEditorInstance.getData())).innerHTML)
};
</script>