在layui中使用CKEditor,前端代码及后台处理代码

引用js



前端代码

 

核心js

//编辑器editor
ClassicEditor
    .create(document.querySelector('#content'), {
        language: 'zh-cn',
        ckfinder: {
            uploadUrl: 'CKEditor/Upload'
        }
    })
    .then(editor => {
        window.editor = editor;
        //监听提交
        form.on('submit(layuiadmin-article-submit)', function (data) {
            var field = data.field; //获取提交的字段
            //获取编辑器内容
            const content = editor.getData();
            if (!content)
                return layer.msg("请编辑内容", { icon: 2 });
            if (!content)
                return layer.msg("内容不可为空", { icon: 2 });
            field = Object.assign(field, { content: content });
            admin.req({
                url: 'article/add'
                , type: 'post'
                , data: { info: field }
                , done(res) {
                    layer.close(index);
                    layui.table.reload('LAY-article-list'); //重载表格
                    //提交完毕销毁editor
                    editor.destroy().catch(error => {
                        console.log(error);
                    });
                }
            });
        });
        form.render();
    })
    .catch(error => {
        console.error(error);
    });

核心方法

//获取ckeditor内容
 var content = editor.getData();
//设置ckeditor内容
 editor.setData(content);
//设置ckeditor编辑器为只读
 editor.isReadOnly = true;

在文章详情页中展示保存的内容的示例(C# MVC中使用)


后台代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace WebApplication.Controllers
{
    public class CKEditorController : Controller
    {
        public IActionResult Upload(List files)
        {
            //https://ckeditor.com/docs/ckeditor5/latest/framework/guides/deep-dive/upload-adapter.html
            var req = Request;
            Dictionary dic = new Dictionary()
            {
                {  "uploaded" , "true" },
                {  "url" , "/favicon.ico" }
            };
            return Json(dic);
        }
    }
}

你可能感兴趣的:(Layui,JavaScript)