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 }

在 ASP.NET MVC 3 中应用 KindEditor的更多相关文章

  1. 【初学者指南】在ASP.NET MVC 5中创建GridView

    介绍 在这篇文章中,我们将会学习如何在 ASP.NET MVC 中创建一个 gridview,就像 ASP.NET Web 表单中的 gridview 一样.服务器端和客户端有许多可用的第三方库,这些 ...

  2. [转]在 ASP.NET MVC 4 中创建为移动设备优化的视图

    原文链接 https://msdn.microsoft.com/zh-cn/magazine/dn296507.aspx 如果深入探讨有关编写移动设备网站的常识性考虑因素,会发现其中有一种内在矛盾.  ...

  3. ASP.NET MVC 4中如何为不同的浏览器自适应布局和视图

    在ASP.NET MVC 4中,可以很简单地实现针对不同的浏览器自适应布局和视图.这个得归功于MVC中的"约定甚于配置"的设计理念. 默认的自适应 MVC 4自动地为移动设备浏览器 ...

  4. 在ASP.NET MVC环境中使用加密与解密

    在.NET Framework 4.5的NET框架中,在程序中加密与解密很方便.现在均学习ASP.NET MVC程序了,因此Insus.NET也在此写个学习的例子.在需要时可以参考与查阅. 写一个Ut ...

  5. 在 ASP.NET MVC 应用中使用 NInject 注入 ASMX 类型的 Web Service

    这几天,有同学问到为什么在 ASP.NET MVC 应用中,无法在 .ASMX 中使用 NInject 进行注入. 现象 比如,我们定义了一个接口,然后定义了一个实现. public interfac ...

  6. 在 ASP.NET MVC 项目中使用 WebForm、 HTML

    原文地址:http://www.cnblogs.com/snowdream/archive/2009/04/17/winforms-in-mvc.html ASP.NET MVC和WebForm各有各 ...

  7. C# 6 与 .NET Core 1.0 高级编程 - 41 ASP.NET MVC(中)

    译文,个人原创,转载请注明出处(C# 6 与 .NET Core 1.0 高级编程 - 41 ASP.NET MVC(中)),不对的地方欢迎指出与交流. 章节出自<Professional C# ...

  8. asp.net MVC 框架中控制器里使用Newtonsoft.Json对前端传过来的字符串进行解析

    下面我用一个实例来和大家分享一下我的经验,asp.net MVC 框架中控制器里使用Newtonsoft.Json对前端传过来的字符串进行解析. using Newtonsoft.Json; usin ...

  9. 在已有的Asp.net MVC项目中引入Taurus.MVC

    Taurus.MVC是一个优秀的框架,如果要应用到已有的Asp.net MVC项目中,需要修改一下. 1.前提约定: 走Taurus.MVC必须指定后缀.如.api 2.原项目修改如下: web.co ...

随机推荐

  1. 007医疗项目-模块一:用户的查找:3.用户表查询的Action和Service

    这里主要写Action和Service. 先写Service层: 架构如下:

  2. 05SpringMvc_映射器SimpleUrlHanderMapping

    这篇文章讲的还是映射器,映射器类有两种,前一篇文章讲的是BeanNameUrlHanderMapping映射器类.今天讲的是SimpleUrlHanderMapping映射器类. 这两个映射器类有什么 ...

  3. 04SpringMvc_映射器_BeanNameUrlHanderMapping

    这篇文章我们讲的是映射器,映射器的作用是什么样的请求交给Action,如果我们没有在xml配置文件中进行配置,默认的就是BeanNameUrlHanderMapping. 我们讲一个案例增加用户的案例 ...

  4. 【转】【C#】ColorMatrix

    ColorMatrix(色彩矩阵),是GDI+里用来调整图片色彩的矩阵. 什么是矩阵,说白了就是C#里的二维数组. 那么这个矩阵调整色彩的原理是什么,他是怎么来调整色彩的呢?这个要从线性代数里的矩阵相 ...

  5. WPF SDK研究 之 AppModel

    Jianqiang's Mobile Dev Blog iOS.Android.WP CnBlogs Home New Post Contact Admin Rss Posts - 528 Artic ...

  6. windows 批处理把所有java源码导入一个txt文件中

    首先在src下搜*.java,把搜到的文件全拷出来放在allsrc目录下, 然后在allsrc目录下建个run.bat,键入以下内容for %%i in (*.java)  do type %%i&g ...

  7. [CareerCup] 2.2 Kth to Last Element of Linked List 链表的倒数第k个元素

    2.2 Implement an algorithm to find the kth to last element of a singly linked list. 这道题让我们求链表中倒数第k个元 ...

  8. [CareerCup] 9.6 Generate Parentheses 生成括号

    9.6 Implement an algorithm to print all valid (e.g., properly opened and closed) combinations of n-p ...

  9. leetcode总结:permutations, permutations II, next permutation, permutation sequence

    Next Permutation: Implement next permutation, which rearranges numbers into the lexicographically ne ...

  10. 一个基于.NET平台的自动化/压力测试系统设计简述

    AutoTest系统设计概述 AutoTest是一个基于.NET平台实现的自动化/压力测试的系统,可独立运行于windows平台下,支持分布式部署,不需要其他配置或编译器的支持.(本质是一个基于协议的 ...