KindEditor 是優秀的開源富文本編輯器,原生支援 PHP、ASP、JSP 等後端,但缺乏官方 ASP.NET 伺服器控制項封裝。本文示範將其封裝為繼承 `TextBox` 的 Web 控制項,支援拖拉設計、屬性設定、主題切換、事件綁定,大幅提升開發效率。
KindEditorForDotNet/
├── KindEditorForDotNet.csproj
├── ConfigHandler.cs // web.config 設定區段處理
├── Editor.cs // 核心控制項類別
├── KindEditor/ // KindEditor 核心檔案 (js, css, themes, plugins, lang)
│ ├── kindeditor.min.js
│ ├── kindeditor.css
│ ├── themes/
│ │ ├── default/
│ │ └── simple/
│ ├── plugins/
│ └── lang/
├── Upload/ // 上傳處理 (ashx)
│ ├── upload_json.ashx
│ └── file_manager_json.ashx
└── LitJSON.dll // JSON 序列化依賴
<configSections>
<section name="KindEditor"
type="KindEditorForDotNet.ConfigHandler, KindEditorForDotNet" />
</configSections>
<KindEditor>
<!-- KindEditor 核心檔案相對路徑 -->
<item key="BasePath" value="~/KindEditor/" />
<!-- 上傳儲存路徑 -->
<item key="UploadPath" value="~/Upload/" />
<!-- 主題預設工具列配置 -->
<item key="Theme:default" value="'source', '|', 'undo', 'redo', '|', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline', 'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist', 'insertunorderedlist', '|', 'emoticons', 'image', 'link'" />
<item key="Theme:simple" value="'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline', 'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist', 'insertunorderedlist', '|', 'emoticons', 'image', 'link'" />
<item key="Theme:book" value="'forecolor', 'hilitecolor', 'bold', 'italic', 'underline','removeformat'" />
</KindEditor>
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
namespace KindEditorForDotNet
{
// 繼承 TextBox 獲得 Text 屬性、驗證器支援、ViewState 等內建功能
[ToolboxData("<{0}:Editor runat=server>{0}:Editor>")]
public class Editor : TextBox
{
// 主題類型:default, simple, book (對應 web.config 設定)
public string ThemeType
{
get => ViewState["ThemeType"]?.ToString() ?? "default";
set => ViewState["ThemeType"] = value;
}
// 客戶端 onchange 事件 (KindEditor 實際為 afterChange)
public string AfterChange
{
get => ViewState["AfterChange"]?.ToString() ?? "";
set => ViewState["AfterChange"] = value;
}
// 上傳路徑覆寫 (可選)
public string UploadPath
{
get => ViewState["UploadPath"]?.ToString() ?? "";
set => ViewState["UploadPath"] = value;
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
// 確保輸出為 textarea (TextBox 預設 TextMode=MultiLine)
this.TextMode = TextBoxMode.MultiLine;
// 註冊 KindEditor 核心腳本 (僅一次)
RegisterKindEditorScripts();
// 產生初始化腳本
string script = GenerateInitScript();
ScriptManager.RegisterStartupScript(this, GetType(), "KE_Init_" + ClientID, script, true);
}
private void RegisterKindEditorScripts()
{
// 從 web.config 讀取基礎路徑
string basePath = GetConfigValue("BasePath", "~/KindEditor/");
basePath = ResolveClientUrl(basePath);
// 註冊核心 JS/CSS (使用 ScriptManager 避免重複)
var sm = ScriptManager.GetCurrent(Page);
if (sm != null)
{
if (!sm.Scripts.Cast().Any(s => s.Path.EndsWith("kindeditor.min.js")))
sm.Scripts.Add(new ScriptReference(basePath + "kindeditor.min.js"));
}
else
{
// 無 ScriptManager 時手動註冊
Page.ClientScript.RegisterClientScriptInclude("KindEditor_Core", basePath + "kindeditor.min.js");
}
// 註冊 CSS
string cssUrl = basePath + "themes/default/default.css";
if (Page.Header != null && !Page.Header.Controls.Cast().Any(c => c is HtmlLink hl && hl.Href == cssUrl))
{
var link = new HtmlLink { Href = cssUrl, Attributes = { ["rel"] = "stylesheet", ["type"] = "text/css" } };
Page.Header.Controls.Add(link);
}
}
private string GenerateInitScript()
{
string basePath = GetConfigValue("BasePath", "~/KindEditor/");
string uploadPath = string.IsNullOrEmpty(UploadPath)
? GetConfigValue("UploadPath", "~/Upload/")
: UploadPath;
string themeConfig = GetConfigValue($"Theme:{ThemeType}", "");
// KindEditor 配置物件
var config = new
{
resizeType = 1,
allowPreviewEmoticons = false,
allowImageUpload = true,
allowFileManager = true,
uploadJson = ResolveClientUrl(uploadPath + "upload_json.ashx"),
fileManagerJson = ResolveClientUrl(uploadPath + "file_manager_json.ashx"),
basePath = ResolveClientUrl(basePath),
items = ParseThemeItems(themeConfig),
afterChange = AfterChange // 使用者自訂回調
};
string json = Newtonsoft.Json.JsonConvert.SerializeObject(config); // 或 LitJSON
return $@"
KindEditor.ready(function(K) {{
window['{ClientID}_editor'] = K.create('#{ClientID}', {json});
}});
";
}
private string[] ParseThemeItems(string themeConfig)
{
// 解析 web.config 中的字串陣列格式: "'item1', 'item2', '|', 'item3'"
if (string.IsNullOrWhiteSpace(themeConfig)) return null;
return themeConfig.Split(',')
.Select(s => s.Trim().Trim('\'', '"'))
.Where(s => !string.IsNullOrEmpty(s))
.ToArray();
}
private string GetConfigValue(string key, string defaultValue)
{
var section = ConfigurationManager.GetSection("KindEditor") as NameValueCollection;
return section?[key] ?? defaultValue;
}
// 重寫 Text 屬性同步 KindEditor 內容
public override string Text
{
get => base.Text;
set
{
base.Text = value;
// 若已初始化,同步更新編輯器內容
string syncScript = $@"
KindEditor.ready(function(K) {{
var editor = K('#{ClientID}');
if (editor) editor.html({Newtonsoft.Json.JsonConvert.SerializeObject(value)});
}});
";
ScriptManager.RegisterStartupScript(this, GetType(), "KE_Sync_" + ClientID, syncScript, true);
}
}
}
}
<%@ WebHandler Language="C#" Class="KindEditorForDotNet.UploadHandler" %>
using System;
using System.Web;
using System.IO;
using Newtonsoft.Json; // 或 LitJSON
namespace KindEditorForDotNet
{
public class UploadHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
var file = context.Request.Files["imgFile"]; // KindEditor 固定參數名
if (file == null || file.ContentLength == 0)
{
context.Response.Write(JsonConvert.SerializeObject(new { error = 1, message = "無檔案" }));
return;
}
// 驗證副檔名
string ext = Path.GetExtension(file.FileName).ToLower();
string[] allowed = { ".jpg", ".jpeg", ".png", ".gif", ".bmp" };
if (!allowed.Contains(ext))
{
context.Response.Write(JsonConvert.SerializeObject(new { error = 1, message = "不支援的格式" }));
return;
}
// 儲存檔案
string uploadDir = context.Server.MapPath(GetConfigValue("UploadPath", "~/Upload/"));
Directory.CreateDirectory(uploadDir);
string fileName = $"{DateTime.Now:yyyyMMddHHmmss}_{Guid.NewGuid():N}{ext}";
string filePath = Path.Combine(uploadDir, fileName);
file.SaveAs(filePath);
// 回傳 KindEditor 要求格式
string fileUrl = VirtualPathUtility.ToAbsolute(GetConfigValue("UploadPath", "~/Upload/")) + fileName;
context.Response.Write(JsonConvert.SerializeObject(new { error = 0, url = fileUrl }));
}
public bool IsReusable => false;
}
}
<%@ Register Assembly="KindEditorForDotNet" Namespace="KindEditorForDotNet" TagPrefix="cc1" %>
0 字元
| 功能 | 實作方式 |
|---|---|
| 唯讀模式 | 設定 `Enabled="false"` → 渲染時 `readonly="readonly"` + JS `editor.readonly()` |
| 字數統計 | `AfterChange="function(){ $('#counter').text(this.count('text')); }"` |
| 自訂工具列 | web.config 新增 `Theme:custom` 或屬性 `CustomItems` 覆寫 |
| 程式碼高亮 | 引入 `prettify` 插件,工具列加入 `code` |
| 表格操作 | 工具列加入 `table` 系列按鈕 |
| 內容過濾 | 後端 `HtmlSanitizer` 淨化 + 前端 `filterMode` 設定 |
將 KindEditor 封裝為 ASP.NET 伺服器控制項,實現了:設計時支援 (拖拉、屬性視窗)、主題系統整合 (web.config 集中管理)、上傳路徑抽象化、客戶端事件暴露 (AfterChange)、Text 屬性雙向同步。雖然 KindEditor 本身已停止更新,但此封裝模式 (繼承 TextBox、ScriptManager 註冊資源、JSON 配置序列化、ASHX 上傳端點) 可套用至任何 JavaScript 富文本編輯器的 ASP.NET 整合專案中。