I have chosen CKEditor as the Rich Text Editor component for my ASP.Net MVC project.
To render the Rich Text Editor is not a problem (quite easy in fact):
@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>
Which renders:
My problem is related with posting the data. If I change the message to: 'The new message' I will still get 'The old message' on my post:
I mean, the viewModel will have a property message which will contain 'The old message' instead of 'The new message'. I've tried to do the following immediately before the post (onBegin):
$('#idRichTextEditor').text(CKEDITOR.instances["idRichTextEditor"].getData());
Or:
$('#idRichTextEditor').val(CKEDITOR.instances["idRichTextEditor"].getData());
Which didn't help... I've also tried:
for (var instanceName in CKEDITOR.instances) {
CKEDITOR.instances["idRichTextEditor"].updateElement();
}
But I seem to be unable to bind the CKEditor's text area with my model. I would like to state that if I turn this rich text area into a common text area I can easily get 'The new message' on the controller side.
I would like to state that despite interesting, and related to my problem, the following stackoverflow's discussions didn't help me much:
CKEditor MVC 3 implementation Help needed
CKEditor and ASP.Net MVC 3 RequiredAttribute
I believe the problem might be related with 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() { // Now you are sure that the data is set. } );
I read this information here: CKEditor 4 documentation
Update: I just realised that when I post the data a second time, the richtext info is correctly binded to the Message property of my viewmodel. This means that I can get what I want if I click the 'save button' twice, but not once...