CKEditor 4 工具教學

 

如何使用CKEditor html編輯器呢?

一、下面範例為CKEditor中的Hello world

<html>
<head>
    <meta charset="utf-8">
    <title>CKEditor</title>
    <script src="http://cdn.ckeditor.com/4.6.1/standard/ckeditor.js"></script>
</head>
<body>
    <textarea name="editor1"></textarea>
    <script>
        CKEDITOR.replace('editor1');
    </script>
</body>
</html>

其中一段CKEDITOR.replace('editor1');程式碼的意思為

將editor1由CKEditor工具取代。

以下html格式都可以用CKEDITOR.replace編輯器化

<textarea name="editor1"></textarea>

<textarea id="editor1"></textarea>

<div id="editor1"></div>

 

CKEDITOR.replace編輯器化的同時,也可對編輯器設定,

如下範例為調整編輯器的介面顏色為草綠色。

<html>
<head>
    <meta charset="utf-8">
    <title>CKEditor</title>
    <script src="http://cdn.ckeditor.com/4.6.1/standard/ckeditor.js"></script>
</head>
<body>
    <textarea name="editor1"></textarea>
    <script>
        CKEDITOR.replace('editor1', {
            uiColor: '#AADC6E'
        });
    </script>
</body>
</html>

相關請參考 replace( element, [config] ) : CKEDITOR.editor

 

另一個為 toolbar 範例

<html>

<head>
    <meta charset="utf-8">
    <title>CKEditor</title>
    <script src="http://cdn.ckeditor.com/4.16.0/full-all/ckeditor.js"></script>
</head>

<body>
    <textarea name="editor1"></textarea>
    <script>
        CKEDITOR.replace('editor1', {
            toolbar: [
                { name: 'document', items: ['Source', '-', 'Save', 'NewPage', 'ExportPdf', 'Preview', 'Print', '-', 'Templates'] },
                { name: 'clipboard', items: ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo'] },
                { name: 'editing', items: ['Find', 'Replace', '-', 'SelectAll', '-', 'Scayt'] },
                { name: 'forms', items: ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField'] },
                '/',
                { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'CopyFormatting', 'RemoveFormat'] },
                { name: 'paragraph', items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl', 'Language'] },
                { name: 'links', items: ['Link', 'Unlink', 'Anchor'] },
                { name: 'insert', items: ['Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak', 'Iframe'] },
                '/',
                { name: 'styles', items: ['Styles', 'Format', 'Font', 'FontSize'] },
                { name: 'colors', items: ['TextColor', 'BGColor'] },
                { name: 'tools', items: ['Maximize', 'ShowBlocks'] },
                { name: 'about', items: ['About'] }
            ]
        });
    </script>
</body>

</html>

 

二、使用getData()取得資料

<html>
<head>
    <meta charset="utf-8">
    <title>CKEditor</title>
    <script src="http://cdn.ckeditor.com/4.6.1/standard/ckeditor.js"></script>
</head>
<body>
    <textarea name="editor1"></textarea>

    <div id="content2" style="display: none" data-sample="2">
        <!-- This <div> will be used to display the editor content. -->
        <div id="editorcontent2">
        </div>
    </div>

    <script data-sample="2">
        (function () {
            var editor2 = CKEDITOR.replace('editor1');
            editor2.on('change', function () {
                document.getElementById('content2').style.display = 'initial';
                document.getElementById('editorcontent2').innerHTML = editor2.getData();
            });
        })();
    </script>
</body>
</html>

請參考 getData( internal ) : String


三、示範資料如何寫到後端

一開始先new一個新的.NET MVC project,

然後刪除不相關的VIEW與Controller,

1、在Index view填入前端post程式

@{
    ViewBag.Title = "Home Page";
}

<script src="http://cdn.ckeditor.com/4.6.1/standard/ckeditor.js"></script>
<textarea name="editor1"></textarea>

<button type="button">送出</button>

<script>
    var dataa = CKEDITOR.replace('editor1');
    $("button").click(function () {
        var s = dataa.getData();

        $.post("Index",
                {
                    title: "Donald Duck",
                    context: htmlEncode(s)
                }
        );
    });

    function htmlEncode(value) {
        //create a in-memory div, set it's inner text(which jQuery automatically encodes)
        //then grab the encoded contents back out.  The div never exists on the page.
        return $('<div/>').text(value).html();
    }
</script>

 

2、在controller加入以下程式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CKEdit_with_MVC.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(string title , string context)
        {
            //資料寫入DB
            return View();
        }
    }
}

 

3、在model加入原本已經做好的edmx檔(model first)

將之前在別的專案所做好的edmx檔複製到現在這Model資料夾來,

只需複製.edmx檔即可

然後會在新專案上看到已複製過來的edmx檔

於diagram按右鍵,Generate Database from Model

選擇要連接的SQL SERVER

完成後於model生成如下檔案

那麼再來看SSMS發現只有Create DB卻沒有Create Table

VS2013Bug嗎?不知道。

我解決的辦法為,將先前所自動產生的CKEditModel.edmx.sql,

裡面的SQL指令複製到SSMS執行即可。

 

4、於view page改用ajax

此範例功能為應用CKEdit並將html原始碼存進資料庫與及時秀同一份文字出來

Index.cshtml內容為

@{
    ViewBag.Title = "Home Page";
}

<script src="http://cdn.ckeditor.com/4.6.1/standard/ckeditor.js"></script>

@using (Html.BeginForm())
{
    @Html.TextArea("editor1", new { name = "editor1" });
    <input id="button" type="button" value="送出">
}

<div id="MyAjax">
</div>

@section scripts{
    <script>
        var dataa = CKEDITOR.replace('editor1');

        function htmlEncode(s) {
            return $("<div/>").text(s).html();
        }

        function GetData() {
            var s = dataa.getData();
            $.ajax({
                type: 'post',
                url: '@Url.Action("Index")',
                data: { context: htmlEncode(s) },
                success: function myfunction(data) {
                    $('#MyAjax').html(s);
                }
            });
        }

        $('#button').on('click', GetData);

    </script>
}

注意$.ajax的url參數要為string,我之前抓Bug抓了好久,

原來我寫成url: @Url.Action("Index"),

沒加雙引號或是單引號就不是字串,請切記。

 

controller的內容為

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CKEdit_with_MVC.Models;

namespace CKEdit_with_MVC.Controllers
{
    public class HomeController : Controller
    {
        CKEditContext db = new CKEditContext();

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(string context)
        {
            //資料寫入DB
            if (db.MyTab.Count() == 0)
            {
                MyTab MyTab = new MyTab();
                MyTab.context = context;
                db.MyTab.Add(MyTab);
            }
            else
            {
                var q = db.MyTab.First();
                q.context = context;
            }
            db.SaveChanges();

            return View();
        }
    }
}

如果要把html標籤post到後端一定要做編碼,

否則資料根本傳不到後端,只能從console端發現

「Failed to load resource: the server responded with a status of 500 (Internal Server Error)」錯誤了

範例檔

 

四、image、image2樣式的差別

如果extraPlugins參數沒指定,或是使用image套件時

<html>
<head>
    <meta charset="utf-8">
    <title>CKEditor</title>
    <script src="http://cdn.ckeditor.com/4.6.1/standard-all/ckeditor.js"></script>
</head>
<body>
    <textarea name="editor1"></textarea>
    <script>
        CKEDITOR.replace('editor1', {
            extraPlugins: ''
        });
    </script>
</body>
</html>

也等於

<html>
<head>
    <meta charset="utf-8">
    <title>CKEditor</title>
    <script src="http://cdn.ckeditor.com/4.6.1/standard-all/ckeditor.js"></script>
</head>
<body>
    <textarea name="editor1"></textarea>
    <script>
        CKEDITOR.replace('editor1', {
            extraPlugins: 'image'
        });
    </script>
</body>
</html>

樣式如下

而使用image2套件的樣式為

<html>
<head>
    <meta charset="utf-8">
    <title>CKEditor</title>
    <script src="http://cdn.ckeditor.com/4.6.1/standard-all/ckeditor.js"></script>
</head>
<body>
    <textarea name="editor1"></textarea>
    <script>
        CKEDITOR.replace('editor1', {
            extraPlugins: 'image2'
        });
    </script>
</body>
</html>

 

參考資料:

Welcome to CKEditor SDK!

CKEditor 4 Developer's Guide

CKEditor in Ajax Applications

ASP.NET MVC 3 使用 CKEditor

ASP.NET MVC 使用 CKEditor.Mvc 與 HtmlEncodeOutput 補充說明

[ASP.net MVC] ckeditor網頁編輯器 字型、圖片上傳功能的快速安裝筆記

其他編輯器:

Summernote - 是以Bootstrap風格為基礎開發的編輯器。

TinyMCE - 是一款老牌的文字編輯器。

Draft.js - 是一款以React開發的編輯器。