在 ASP.NET MVC 3 中应用 KindEditor
生活随笔
收集整理的這篇文章主要介紹了
在 ASP.NET MVC 3 中应用 KindEditor
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
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) |
第三步
在需要應(yīng)用編輯器的Model屬性中設(shè)置 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 //創(chuàng)建文件夾
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 //根據(jù)path參數(shù),設(shè)置各路徑和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 } 創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎
總結(jié)
以上是生活随笔為你收集整理的在 ASP.NET MVC 3 中应用 KindEditor的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到亲人吵架什么预兆
- 下一篇: 女人梦到活捉蝎子什么征兆