Search code examples
javascriptc#asp.net-coreckeditor

How can we populate textarea value when textarea is initilized as ckeditor


Well i have been working on CKEDITOR with HTML FORMS and backend is asp.net core v3.1. I have used asp tag helpers in rendering and binding html forms.

Following is the code :

 <div class="form-group">
                                <label asp-for="Content" class="control-label"></label>
                                <div class="input-group">
                                
                                    <textarea asp-for="Content" class="form-control" required placeholder="Content"></textarea>
                                    <span asp-validation-for="Content" class="text-danger"></span>
                                </div>
                            </div>

I have two pages create and edit which creates the first form entry to database and update the values respectively.

So when i load edit page all the values are loaded but CKEditor values are not loaded after all it is bound to textarea.

Values are not displaying in HTML CKEDITOR content area.

CKEDITOR INITILIZE CODE IS BELOW

  <script>
        // Replace the <textarea id="editor1"> with a CKEditor
        // instance, using default configuration.
        $(function () {
         CKEDITOR.replace('Content');        
        })
       
    </script>
}

Solution

  • The API documentation has documented methods for this:

    1. Set Data

      setData.
    CKEDITOR.instances.editor1.setData( '<p>This is the editor data.</p>' );
    
    1. Insert Element

      insertElement.
    var element = CKEDITOR.dom.element.createFromHtml( '<img src="hello.png" border="0" title="Hello" />' );
    CKEDITOR.instances.editor1.insertElement( element );
    
    1. Insert Text

      insertText.
    CKEDITOR.instances.editor1.insertText( ' line1 \n\n line2' );
    
    1. Insert Html

      insertHtml.

    CKEDITOR.instances.editor1.insertHtml( '<p>This is a new paragraph.</p>' );
    

    I think what you need is setData as the other methods append text/html at the cursor position.