標籤:c style class blog code java
文字編輯器有很多,比如ticymce和CKEditor就比較好用,但涉及到圖片、檔案上傳,需要結合CKFinder實現,而且有些功能是收費的,即使有意付費使用, 支付也不方便。好在百度的開源文字編輯器UEditor現在也發展得不錯,本篇就來體驗其在MVC中的使用。需要實現如下效果:
1、上傳圖片
2、上傳塗鴉
3、字數限制
4、另一視圖頁圖文顯示
首先到這裡下載UEditor的.NET版本,我下載的是[1.4.3.NET版本]的UTF-8版。
下載後,在Scripts檔案夾下建立UEditor檔案夾,把所有下載文檔都放到UEditor檔案夾中。
我們需要一個Model,用[DataType(DataType.MultilineText)]來指定某字串類型屬性使用TextArea來顯示。
using System.ComponentModel.DataAnnotations;namespace MvcApplication2.Models{ public class Post { [Required(ErrorMessage = "必填")] [DataType(DataType.MultilineText)] public string Content { get; set; } }}
HomeController中,一個Action用來顯示強型別視圖,另一個Action,當驗證通過顯示Result.cshtml部分視圖。
using System.Web.Mvc;using MvcApplication2.Models;namespace MvcApplication2.Controllers{ public class HomeController : Controller { public ActionResult Create() { return View(); } [HttpPost] [ValidateInput(false)] public ActionResult Create(Post post) { if (ModelState.IsValid) { ViewData["c"] = post.Content; return PartialView("Result"); } return View(post); } }}
Result.cshtml部分視圖顯示圖文資訊。
@Html.Raw(ViewData["c"].ToString())
Home/Create.cshtml中,讓TextArea呈現編輯器,通過addListener()方法為編輯器添加偵聽contentChange事件方法,當字數超出限制(這裡是100),就讓編輯器執行一個後援動作:editor.execCommand("undo")。另外,還通過 Window.UEDITOR_HOME_URL = "/Scripts/UEditor/"設定了UEditor的根路徑,這裡的設定最終會賦值給ueditor.config.js中UEDITOR_HOME_URL屬性。
@model MvcApplication2.Models.Post@{ Layout = null;}<!DOCTYPE html><html><head> <meta name="viewport" content="width=device-width" /> <title>Create</title> <link href="~/Scripts/UEditor/themes/default/css/ueditor.css" rel="stylesheet" /> <script src="~/Scripts/jquery-1.8.2.js"></script> <script src="~/Scripts/UEditor/ueditor.config.js"></script> <script src="~/Scripts/UEditor/ueditor.all.js"></script> <script type="text/javascript"> $(function() { Window.UEDITOR_HOME_URL = "/Scripts/UEditor/"; var editor = new baidu.editor.ui.Editor(); editor.render("Content"); editor.addListener("contentChange", function() { if (editor.getContentLength(true) > 100) { editor.execCommand("undo"); } }); }); </script></head><body> <div> @using (Html.BeginForm("Create", "Home", FormMethod.Post, new { id = "addForm" })) { @Html.EditorFor(model => model.Content) <br/> <input type="submit" value="提交"/> } </div></body></html>
圖片的上傳路徑在config.json中設定。
以上,從imageUrlPrefix和imagePathFormat或scrawlPathFormat設定大致可以看出圖片的儲存路徑是:Scripts/UEditor/net/upload/image/20140607/6353775730679106479709368.jpg,為此,我們需要在Scripts/UEditor/net下建立upload檔案夾,再在Scripts/UEditor/net/upload下建立image檔案夾。
最後在ueditor.config.js中設定UEditor的全域路徑、一般處理常式的路徑、字數限制,等等。