4

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:

RichTextArea correctly rendering my Model.MessageDiffusion.Message property

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:

The controller's HttpPost action

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...

Community
  • 1
  • 1
Luis Gouveia
  • 8,334
  • 9
  • 46
  • 68

1 Answers1

4

I guess I just didn't search well enough on StackOverFlow, which indeed has an answer for everything. The right answer is:

$('#YOURFORMID').on('submit', function(){
    for ( instance in CKEDITOR.instances ) {
        CKEDITOR.instances[instance].updateElement();
    }
});

Which I found here:

CKEDITOR doesn't submit data via ajax on first submit

Community
  • 1
  • 1
Luis Gouveia
  • 8,334
  • 9
  • 46
  • 68