首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET MVC 整合 FCKeditor 富文本編輯器完整步驟

     編輯:關於ASP.NET

ASP.NET MVC 無 Server Control 概念,無法像 WebForms 直接拖曳 FCKeditor。本文說明如何在 MVC 專案中手動引用、初始化並取得 FCKeditor 內容。

為什麼 MVC 無法直接使用 WebForms 控制項

  • WebForms:.aspx + .aspx.cs CodeBehind,控制項 ID 直接對應伺服端物件
  • MVC:View 只有 HTML 標記,Controller 透過 Model Binding 取值,無控制項實例

MVC 表單提交兩種取值方式

// 方式 1:Action 參數直接繫結 (名稱需與表單 name 一致)
[HttpPost]
public ActionResult Create(string txtTitle, string txtContent) { ... }

// 方式 2:FormCollection 手動取值
[HttpPost]
public ActionResult Create(FormCollection form) {
    string title = form["txtTitle"];
    string content = form["txtContent"];
}

專案目錄結構與檔案放置

專案目錄結構

/Scripts/fckeditor/          // FCKeditor 核心檔案
/Content/FCKeditorConfig.js  // 自訂設定檔
/Views/Shared/EditorTemplates/FCKEditor.cshtml  // 編輯器部分檢視

View 中引用與初始化 FCKeditor

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<ArticleModel>" %>

<asp:Content ContentPlaceHolderID="MainContent" runat="server">
    <script type="text/javascript" src="<%= Url.Content("~/Scripts/fckeditor/fckeditor.js") %>"></script>
    
    <form method="post" action="<%= Url.Action("Create") %>">
        <label>標題:</label>
        <input type="text" name="Title" value="<%= Model.Title %>" /><br/>
        
        <label>內容:</label>
        <textarea name="Content" id="Content" rows="10" cols="80"><%= Model.Content %></textarea>
        <script type="text/javascript">
            var oFCKeditor = new FCKeditor('Content');
            oFCKeditor.BasePath = '<%= Url.Content("~/Scripts/fckeditor/") %>';
            oFCKeditor.Config.CustomConfigurationsPath = '<%= Url.Content("~/Content/FCKeditorConfig.js") %>';
            oFCKeditor.Value = document.getElementById('Content').value; // 初始值
            oFCKeditor.Create();
        </script>
        
        <input type="submit" value="送出" />
    </form>
</asp:Content>

Controller 接收內容

[HttpPost]
[ValidateInput(false)] // 允許 HTML 內容,需自行防 XSS
public ActionResult Create(ArticleModel model) {
    // model.Content 即為 FCKeditor 提交的 HTML 字串
    if (ModelState.IsValid) {
        articleService.Save(model);
        return RedirectToAction("Index");
    }
    return View(model);
}

關鍵設定:FCKeditorConfig.js

FCKConfig.ToolbarSets["Default"] = [
    ['Source', 'DocProps', '-', 'Save', 'NewPage', 'Preview', '-', 'Templates'],
    ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteWord', '-', 'Print', 'SpellCheck'],
    ['Undo', 'Redo', '-', 'Find', 'Replace', '-', 'SelectAll', 'RemoveFormat'],
    ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField'],
    '/',
    ['Bold', 'Italic', 'Underline', 'StrikeThrough', '-', 'Subscript', 'Superscript'],
    ['OrderedList', 'UnorderedList', '-', 'Outdent', 'Indent', '-', 'Blockquote'],
    ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyFull'],
    ['Link', 'Unlink', 'Anchor'],
    ['Image', 'Flash', 'Table', 'Rule', 'Smiley', 'SpecialChar', 'PageBreak'],
    '/',
    ['Style', 'FontFormat', 'FontName', 'FontSize'],
    ['TextColor', 'BGColor'],
    ['FitWindow', 'ShowBlocks', '-', 'About']
];

FCKConfig.EnterMode = 'p'; // Enter 產生 

FCKConfig.ShiftEnterMode = 'br'; // Shift+Enter 產生
FCKConfig.FullPage = false; FCKConfig.StartupFocus = true;

安全性注意事項

  • XSS 防護:[ValidateInput(false)] 開啟後,必須在輸出時使用 Html.Sanitize() (如 HtmlSanitizer 套件) 或儲存前過濾危險標籤
  • 上傳功能:FCKeditor 內建上傳需配合伺服端處理程式 (FileManagerConnector),MVC 需自行實作對應 Action
  • 建議替代:FCKeditor 已停止更新,新專案建議使用 CKEditor 4/5、TinyMCE 或 Quill,支援現代模組化載入

CKEditor 5 整合範例 (現代替代)

<textarea name="Content" id="editor"><%= Model.Content %></textarea>
<script src="<%= Url.Content("~/lib/ckeditor5/ckeditor.js") %>"></script>
<script>
    ClassicEditor
        .create(document.querySelector('#editor'), {
            toolbar: ['heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', 'blockQuote']
        })
        .catch(error => console.error(error));
</script>
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved