Friday, September 20, 2013

Using CKEditor in your MVC project

CKEditor is an Amazing Rich Text Editor to be used in your MVC Applications. I had implemented that one of my forms and was bent over to implement it throughout the project, replacing the existing editor which was little buggy.

Implementation has been made very easy with the release of the newer version of CKEditor 4

First you need to use the HTMLHelpers to create a Text Area:

@Html.TextArea("controlid", "controlvalue")   


Then place your CKEditor javascript script below the control. This will replace the TextArea with the Editor

CKEDITOR.replace('controlid', {
                uiColor: '#808080',
                height: '120px',
                toolbar: [
           ['Bold', 'Italic', 'Underline', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink', '-', 'Image', 'Table'],
           ['FontSize', 'TextColor', 'BGColor', 'Source'],
                //                                ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock']
          ]
            });


Form submission is magically taken care of by MVC Approach on postback

But all that was not plain and simple on Ajax based submissions. I had some trouble implementing it on one of the Ajax based forms. This is what I did based upon the CKEditor API
the click of the submit button.

$(document).ready(function() {

    $("#btnSubmit").click(function(){

        $("#controlid").val(CKEDITOR.instances["controlid"].getData());

    });

});


And I had Success at last!

No comments: