ASP.NET MVC 中使用 CKEditor 4.10

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%;
}

这样显示出来的图片就会宽度自适应了。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值