http://www.cnblogs.com/weicong/archive/2012/03/31/2427608.html
第一步
将 KindEditor 的源文件添加到项目中,建议放到 /Scripts/kindeditor 目录中,其中只需要有 lang目录、plugis目录、themes目录和kindeditor-min.js文件即可。
第二步
在 /Views/Shared/EditorTemplates 目录中添加一个分部视图“kindeditor.cshtml”(文件名可任意)。代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | < script type="text/javascript" src="http://mce_host/weicong/admin/@Url.Content("></ script > < script type="text/javascript" src="http://mce_host/weicong/admin/@Url.Content("></ script > < script type="text/javascript">// <![CDATA[ (function () { KindEditor.ready(function (k) { k.create("#@ViewData.TemplateInfo.GetFullHtmlFieldName(string.Empty)", { themeType: 'default', width: '690px', height: '400px', uploadJson: '/KindEditorHandler/Upload', allowFileManager: true, fileManagerJson: '/KindEditorHandler/FileManager' }); }); })(); // ]]></ script > @Html.TextArea(string.Empty, ViewData.TemplateInfo.FormattedModelValue) |
第三步
在需要应用编辑器的Model属性中设置 DataAnnotations,比如:
1 2 3 4 | [DisplayName( "正文" )] [AllowHtml] [UIHint( "kindeditor" )] // EditorTemplates 目录中添加的视图名称 public object Content { get ; set ; } |
第四步
在视图中使用 @Html.EditorFor(model => model.Content) 即可加载编辑器。
附 KindEditorHandlerController 源码
1 using System;
2 using System.Collections;
3 using System.Collections.Generic;
4 using System.Globalization;
5 using System.IO;
6 using System.Text.RegularExpressions;
7 using System.Web.Mvc;
8
9 namespace KwDoctorCourse.Controllers
10 {
11 public class KindEditorHandlerController : Controller
12 {
13 //文件保存目录路径
14 const string SavePath = "/uploadfile/";
15
16 #region uploadJson
17
18 //
19 // GET: /KindEditorHandler/Upload
20
21 public ActionResult Upload()
22 {
23 文件保存目录路径
24 //const string savePath = "/Content/Uploads/";
25
26 //文件保存目录URL
27 var saveUrl = SavePath;
28
29 //定义允许上传的文件扩展名
30 var extTable = new Hashtable
31 {
32 {"image", "gif,jpg,jpeg,png,bmp"},
33 {"flash", "swf,flv"},
34 {"media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb"},
35 {"file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2"}
36 };
37
38 //最大文件大小
39 const int maxSize = 2000000;
40
41 var imgFile = Request.Files["imgFile"];
42
43 if (imgFile == null)
44 {
45 return ShowError("请选择文件。");
46 }
47
48 var dirPath = Server.MapPath(SavePath);
49 if (!Directory.Exists(dirPath))
50 {
51 //return ShowError("上传目录不存在。" + dirPath);
52 Directory.CreateDirectory(dirPath);
53 }
54
55 var dirName = Request.QueryString["dir"];
56 if (String.IsNullOrEmpty(dirName))
57 {
58 dirName = "image";
59 }
60
61 if (!extTable.ContainsKey(dirName))
62 {
63 return ShowError("目录名不正确。");
64 }
65
66 var fileName = imgFile.FileName;
67 var extension = Path.GetExtension(fileName);
68 if (extension == null)
69 {
70 return ShowError("extension == null");
71 }
72
73 var fileExt = extension.ToLower();
74
75 if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize)
76 {
77 return ShowError("上传文件大小超过限制。");
78 }
79
80 if (String.IsNullOrEmpty(fileExt) ||
81 Array.IndexOf(((String)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1)
82 {
83 return ShowError("上传文件扩展名是不允许的扩展名。\n只允许" + ((String)extTable[dirName]) + "格式。");
84 }
85
86 //创建文件夹
87 dirPath += dirName + "/";
88 saveUrl += dirName + "/";
89 if (!Directory.Exists(dirPath))
90 {
91 Directory.CreateDirectory(dirPath);
92 }
93 var ymd = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
94 dirPath += ymd + "/";
95 saveUrl += ymd + "/";
96 if (!Directory.Exists(dirPath))
97 {
98 Directory.CreateDirectory(dirPath);
99 }
100
101 var newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
102 var filePath = dirPath + newFileName;
103
104 imgFile.SaveAs(filePath);
105
106 var fileUrl = saveUrl + newFileName;
107
108 var hash = new Hashtable();
109 hash["error"] = 0;
110 hash["url"] = fileUrl;
111
112 return Json(hash, "text/html;charset=UTF-8");
113 }
114
115 private JsonResult ShowError(string message)
116 {
117 var hash = new Hashtable();
118 hash["error"] = 1;
119 hash["message"] = message;
120
121 return Json(hash, "text/html;charset=UTF-8");
122 }
123
124 #endregion
125
126 #region fileManagerJson
127
128 //
129 // GET: /KindEditorHandler/FileManager
130
131 public ActionResult FileManager()
132 {
133 根目录路径,相对路径
134 //String rootPath = "/Content/Uploads/";
135
136 //根目录URL,可以指定绝对路径,比如 http://www.yoursite.com/attached/
137 var rootUrl = SavePath;
138
139 //图片扩展名
140 const string fileTypes = "gif,jpg,jpeg,png,bmp";
141
142 String currentPath;
143 String currentUrl;
144 String currentDirPath ;
145 String moveupDirPath ;
146
147 var dirPath = Server.MapPath(SavePath);
148 var dirName = Request.QueryString["dir"];
149 if (!String.IsNullOrEmpty(dirName))
150 {
151 if (Array.IndexOf("image,flash,media,file".Split(','), dirName) == -1)
152 {
153 return Content("Invalid Directory name.");
154 }
155 dirPath += dirName + "/";
156 rootUrl += dirName + "/";
157 if (!Directory.Exists(dirPath))
158 {
159 Directory.CreateDirectory(dirPath);
160 }
161 }
162
163 //根据path参数,设置各路径和URL
164 var path = Request.QueryString["path"];
165 path = String.IsNullOrEmpty(path) ? "" : path;
166 if (path == "")
167 {
168 currentPath = dirPath;
169 currentUrl = rootUrl;
170 currentDirPath = "";
171 moveupDirPath = "";
172 }
173 else
174 {
175 currentPath = dirPath + path;
176 currentUrl = rootUrl + path;
177 currentDirPath = path;
178 moveupDirPath = Regex.Replace(currentDirPath, @"(.*?)[^\/]+\/$", "$1");
179 }
180
181 //排序形式,name or size or type
182 String order = Request.QueryString["order"];
183 order = String.IsNullOrEmpty(order) ? "" : order.ToLower();
184
185 //不允许使用..移动到上一级目录
186 if (Regex.IsMatch(path, @"\.\."))
187 {
188 return Content("Access is not allowed.");
189 }
190
191 //最后一个字符不是/
192 if (path != "" && !path.EndsWith("/"))
193 {
194 return Content("Parameter is not valid.");
195 }
196 //目录不存在或不是目录
197 if (!Directory.Exists(currentPath))
198 {
199 return Content("Directory does not exist.");
200 }
201
202 //遍历目录取得文件信息
203 string[] dirList = Directory.GetDirectories(currentPath);
204 string[] fileList = Directory.GetFiles(currentPath);
205
206 switch (order)
207 {
208 case "size":
209 Array.Sort(dirList, new NameSorter());
210 Array.Sort(fileList, new SizeSorter());
211 break;
212 case "type":
213 Array.Sort(dirList, new NameSorter());
214 Array.Sort(fileList, new TypeSorter());
215 break;
216 default:
217 Array.Sort(dirList, new NameSorter());
218 Array.Sort(fileList, new NameSorter());
219 break;
220 }
221
222 var result = new Hashtable();
223 result["moveup_dir_path"] = moveupDirPath;
224 result["current_dir_path"] = currentDirPath;
225 result["current_url"] = currentUrl;
226 result["total_count"] = dirList.Length + fileList.Length;
227 var dirFileList = new List<Hashtable>();
228 result["file_list"] = dirFileList;
229 foreach (var t in dirList)
230 {
231 var dir = new DirectoryInfo(t);
232 var hash = new Hashtable();
233 hash["is_dir"] = true;
234 hash["has_file"] = (dir.GetFileSystemInfos().Length > 0);
235 hash["filesize"] = 0;
236 hash["is_photo"] = false;
237 hash["filetype"] = "";
238 hash["filename"] = dir.Name;
239 hash["datetime"] = dir.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
240 dirFileList.Add(hash);
241 }
242 foreach (var t in fileList)
243 {
244 var file = new FileInfo(t);
245 var hash = new Hashtable();
246 hash["is_dir"] = false;
247 hash["has_file"] = false;
248 hash["filesize"] = file.Length;
249 hash["is_photo"] = (Array.IndexOf(fileTypes.Split(','), file.Extension.Substring(1).ToLower()) >= 0);
250 hash["filetype"] = file.Extension.Substring(1);
251 hash["filename"] = file.Name;
252 hash["datetime"] = file.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
253 dirFileList.Add(hash);
254 }
255
256 return Json(result, "text/html;charset=UTF-8", JsonRequestBehavior.AllowGet);
257 }
258
259
260 private class NameSorter : IComparer
261 {
262 public int Compare(object x, object y)
263 {
264 if (x == null && y == null)
265 {
266 return 0;
267 }
268 if (x == null)
269 {
270 return -1;
271 }
272 if (y == null)
273 {
274 return 1;
275 }
276 var xInfo = new FileInfo(x.ToString());
277 var yInfo = new FileInfo(y.ToString());
278
279 return String.CompareOrdinal(xInfo.FullName, yInfo.FullName);
280 }
281 }
282
283 private class SizeSorter : IComparer
284 {
285 public int Compare(object x, object y)
286 {
287 if (x == null && y == null)
288 {
289 return 0;
290 }
291 if (x == null)
292 {
293 return -1;
294 }
295 if (y == null)
296 {
297 return 1;
298 }
299 var xInfo = new FileInfo(x.ToString());
300 var yInfo = new FileInfo(y.ToString());
301
302 return xInfo.Length.CompareTo(yInfo.Length);
303 }
304 }
305
306 private class TypeSorter : IComparer
307 {
308 public int Compare(object x, object y)
309 {
310 if (x == null && y == null)
311 {
312 return 0;
313 }
314 if (x == null)
315 {
316 return -1;
317 }
318 if (y == null)
319 {
320 return 1;
321 }
322 var xInfo = new FileInfo(x.ToString());
323 var yInfo = new FileInfo(y.ToString());
324
325 return String.CompareOrdinal(xInfo.Extension, yInfo.Extension);
326 }
327 }
328
329 #endregion
330 }
331 }