MVC: binding CKEditor textbox value to model
I selected CKEditor as the Rich Text Editor component for my ASP.Net MVC project.
For Rich Text Editor rendering, this is not a problem (quite simple):
@Html.TextAreaFor(model => model.MessageDiffusion.Message, new { @id = idRichTextEditor })
<script type="text/javascript">
$(document).ready(function () {
// Rich Text Editor (CKEditor) Configuration
CKEDITOR.replace(
idRichTextEditor, {
language: 'fr'
}
);
});
</script>
What is he doing:
My problem is with sending data. If I change the message to: "New message" I still get "Old message" in my message:
I mean the viewModel will have a property message that will contain "Old message" instead of "New message". I tried to do the following just before the message (onBegin):
$('#idRichTextEditor').text(CKEDITOR.instances["idRichTextEditor"].getData());
Or:
...$ ('# idRichTextEditor') Shaft (CKEDITOR.instances ["idRichTextEditor"] GetData ().);
Which didn't help ... I also tried:
for (var instanceName in CKEDITOR.instances) {
CKEDITOR.instances["idRichTextEditor"].updateElement();
}
But I can't seem to link the CKEditor textarea to my model. I would like to say that if I turn this rich text area into a general text area, I can easily get a "New Message" on the controller side.
I would like to state that, despite being interesting and related to my problem, the following stackoverflow discussions did not help me much:
CKEditor MVC 3 Implementation Help Needed
CKEditor and ASP.Net MVC 3 Required Attribute
I believe that the problem may be related to the fact that
setting data in CKEditor is an asynchronous operation, val ('some data') will return a jQuery Promise object if any of the elements is an editor. You can use it with jQuery helpers: $ .when ($ ('#editor'). Val ('foo')). then (function () {// You are now sure the data is set.});
I read this information here: CKEditor 4 Documentation
Update . I just figured out that when I submit data a second time, the richtext information is correctly bound to the Message property of my viewmodel. This means that I can get what I want if I hit the Save button twice, but not once ...
source to share