1. 在项目中添加CKEditor
将下载下来的压缩包解压后保持目录结构不变添加到项目中,不过sample文件夹是不需要的。
2. 在视图中使用CKEditor
先在BundleConfig.cs中添加:
bundles.Add(new ScriptBundle("~/bundles/ckeditor").Include(
"~/Include/CKEditor/ckeditor.js"));
然后在视图文件中添加引用:
@Scripts.Render("~/bundles/ckeditor")
接着在需要使用CKEditor的地方使用:
@Html.TextAreaFor(model => model.Content, new { @class = "ckeditor" })
运行效果如下:
3. 添加图片上传功能
在配置文件config.js中添加行:
config.filebrowserImageUploadUrl = "/Manage/Upload";
现在点击图片按钮就可以看到上传选项卡了
接着去除“高级”选项卡并清空图片预览里的文字,在config.js中添加行:
config.removeDialogTabs = 'image:advanced;link:advanced';
config.image_previewText = ' ';
效果如下:
4. 后端实现图片上传功能
[HttpPost]
[AdminAuthorize]
public JsonResult Upload(HttpPostedFileBase upload)
{
string savePath = "/Attached/";
string dirPath = Server.MapPath(savePath);
//如果目录不存在则创建目录
if (!Directory.Exists(dirPath))
Directory.CreateDirectory(dirPath);
//获取图片文件名及扩展名
var fileName = Path.GetFileName(upload.FileName);
string fileExt = Path.GetExtension(fileName).ToLower();
//用时间来生成新文件名并保存
string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
upload.SaveAs(dirPath + "/" + newFileName);
//上传成功后,我们还需要返回Json格式的响应
return Json(new {
uploaded = 1,
fileName = newFileName,
url = savePath + newFileName
});
}
因为MVC默认不允许输入HTML标签,所以需要为编辑器提交内容的目标Action添加特性[ValidateInput(false)]。
需要显示内容时,可以使用
@Html.Raw(Model.Content)
5. 解决CKEditor图片宽度自适应的问题
在配置文件config.js中添加行:
config.disallowedContent = 'img{width,height};img[width,height]';
然后使用CSS样式:
p img {
width: auto;
height: auto;
max-width: 100%;
}
这样显示出来的图片就会宽度自适应了。