MVC中使用CKEditor01-基础
本篇体验在MVC中使用CKEditor,仅仅算思路、基础,暂没有把验证等与CKEditor结合在一起考虑。
□ 1 使用NUGET引入CKEditor
PM> Install-Package CKEditor
引入后在Scripts中有了CKEditor的相关文件:
□ 2 View Model
using System.ComponentModel.DataAnnotations;
namespace MvcCKEditor.Models
{
public class Article
{
public int ID { get; set; }
[Required]
[Display(Name = "主题")]
public string Subject { get; set; }
[Required]
[Display(Name = "内容")]
public string Content { get; set; }
}
}
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
□ 3 不管在哪里引用,必须引用以下有关CKEditor的js文件
<script src="@Url.Content("~/Scripts/ckeditor/ckeditor.js")" type="text/javascript"></script>
□ 4 HomeController
有关显示添加视图和接收添加内容:
接收添加内容时,是通过把Dictionary<string,string>,把所有错误以键值对的形式放到这个字典集合里,再使用Newtonsoft.Json把这个集合转换成json字符串,最后让前台jquery判断。但在实际做项目中,可能用ModelState在后台验证,并把需要验证的部分放在部分视图里,可能更方便一些,暂不深究。
就像在ASP.NET WebForm开发的时,如果页面没有设置ValidateInput=false,就会出现警告。在MVC中如果不设置,也会报如下错:
设置允许CKEditor有2种方式:
1、在控制器方法
[ValidateInput(false)]
public ActionResult Create(string subject, string content)
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
2、Scripts/ckeditor/config.js中做全局设置
CKEDITOR.editorConfig = function( config )
{
// Define changes to default configuration here. For example:
// config.language = 'fr';
// config.uiColor = '#AADC6E';
//也可以在这里做全局设置
//config.htmlEncodeOutput = true;
};
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
控制器与方法:
展开using System.Web.Mvc;
using MvcCKEditor.Models;
using Newtonsoft.Json; namespace MvcCKEditor.Controllers
{
public class HomeController : Controller
{
private List<Article> articles = null; public HomeController()
{
articles = new List<Article>
{
new Article(){ID =1,Subject = "主题1",Content = "内容1"},
new Article(){ID = 2,Subject = "主题2",Content = "内容2"}
};
} public ActionResult Index()
{ return View(articles);
} public ActionResult Create()
{
return View();
} [HttpPost]
//[ValidateAntiForgeryToken]
[ValidateInput(false)]
public ActionResult Create(string subject, string content)
{
Dictionary<string,string> jo = new Dictionary<string, string>();
if (string.IsNullOrEmpty(subject))
{
jo.Add("Msg","没有输入标题 ");
return Content(JsonConvert.SerializeObject(jo), "application/json");
}
if (string.IsNullOrEmpty(content))
{
jo.Add("Msg", "没有输入内容 ");
return Content(JsonConvert.SerializeObject(jo), "application/json");
}
try
{
Article article = new Article();
article.Subject = subject;
article.Content = content;
articles.Add(article);
jo.Add("Result","Success");
}
catch (Exception ex)
{
jo.Add("Result","Failure");
jo.Add("ResultMessage", ex.Message);
}
return Content(JsonConvert.SerializeObject(jo), "application/json");
}
}
}
□ 5 Create.cshtml视图
获取CKEditor内容:
不能用var content = $('#content').val();获取CKEditor的内容。
因为TextArea的内容已经被CKEdtor替换掉了:var editor = CKEDITOR.editor.replace('content', { skin: 'kama', width: '800px' });
应该使用如下方式来获取CKEditor的内容:var content = editor.getData();
展开@model MvcCKEditor.Models.Article
@{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Create</h2>
@using (Html.BeginForm("Create","Home",FormMethod.Post,new {id = "FormCreate"}))
{
@Html.ValidationSummary(true)
@Html.AntiForgeryToken()
<fieldset>
<legend>Article</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Subject)
</div>
<div class="editor-field">
@Html.TextBox("subject",null,new {id="subject",style="width:400px",MaxLength="100"})
@Html.ValidationMessageFor(model => model.Subject)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Content)
</div>
<div class="editor-field">
@Html.TextArea("content",new {id="content", @name="content"})
@Html.ValidationMessageFor(model => model.Content)
</div>
<p>
<input type="button" value="创建" id="ButtonCreate" />
@*<input type="submit" value="创建"/>*@
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
var editor = CKEDITOR.editor.replace('content', {
skin: 'kama',
width: '800px'
});
$(function () {
$('#ButtonCreate').click(function () {
createArticle();
});
});
function createArticle() {
var subject = $.trim($('#subject').val());
var content = editor.getData();
if (subject.length == 0) {
alert('请输入标题');
return false;
}
if (content.length == 0) {
alert('请输入内容');
return false;
}
$.ajax({
url: '@Url.Action("Create", "Home")',
type: 'post',
data: { subject: subject, content: content },
cache: false,
async: false,
dataType: 'json',
success: function(data) {
if (data.Msg) {
alert(data.Msg);
return false;
} else {
if (data.Result == 'Success') {
alert('Success');
location.href = '@Url.Action("Index", "Home")';
} else {
alert(data.ResultMessage);
return false;
}
}
}
});
}
</script>
}
结果:
参考资料:
※ ASP.NET MVC 3 使用CKEditor
MVC中使用CKEditor01-基础的更多相关文章
- .NetCore MVC中的路由(1)路由配置基础
.NetCore MVC中的路由(1)路由配置基础 0x00 路由在MVC中起到的作用 前段时间一直忙于别的事情,终于搞定了继续学习.NetCore.这次学习的主题是MVC中的路由.路由是所有MVC框 ...
- Mvc中使用MvcSiteMapProvider实现站点地图之基础篇
MvcSiteMapProvider 是针对 ASP.NET MVC 中,提供菜单. 网站地图. 站点地图路径功能,以及更多的工具.它提供配置使用一个可插入的体系结构,可以是 XML. 数据库或动态生 ...
- js基础 js自执行函数、调用递归函数、圆括号运算符、函数声明的提升 js 布尔值 ASP.NET MVC中设置跨域
js基础 目录 javascript基础 ESMAScript数据类型 DOM JS常用方法 回到顶部 javascript基础 常说的js包括三个部分:dom(文档document).bom(浏览器 ...
- .net 开源模板引擎jntemplate 教程:基础篇之在ASP.NET MVC中使用Jntemplate
在ASP.NET MVC 中使用Jntemplate 上一篇我们详细介绍了jntemplate的标签语法,本篇文章将继续介绍如何在ASP.NET MVC 中使用Jntemplate. 一.使用Jnte ...
- 4.在MVC中使用仓储模式进行增删查改
原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-using-the-repository-pattern-in-mvc/ 系列目录: ...
- 如何在ASP.NET Core中实现一个基础的身份认证
注:本文提到的代码示例下载地址> How to achieve a basic authorization in ASP.NET Core 如何在ASP.NET Core中实现一个基础的身份认证 ...
- MVC中使用Entity Framework 基于方法的查询学习笔记 (二)
解释,不解释: 紧接上文,我们在Visual Studio2012中看到系统为我们自动创建的视图(View)文件Index.cshtml中,开头有如下这句话: @model IEnumerable&l ...
- [转]如何在ASP.NET Core中实现一个基础的身份认证
本文转自:http://www.cnblogs.com/onecodeonescript/p/6015512.html 注:本文提到的代码示例下载地址> How to achieve a bas ...
- AspNet MVC中各种上下文理解
0 前言 AspNet MVC中比较重要的上下文,有如下: 核心的上下文有HttpContext(请求上下文),ControllerContext(控制器上下文) 过滤器有关有五个的上下文Actio ...
- MVC5+EF6 入门完整教程十一:细说MVC中仓储模式的应用
摘要: 第一阶段1~10篇已经覆盖了MVC开发必要的基本知识. 第二阶段11-20篇将会侧重于专题的讲解,一篇文章解决一个实际问题. 根据园友的反馈, 本篇文章将会先对呼声最高的仓储模式进行讲解. 文 ...
随机推荐
- opencv(2)绘图
绘制直线 函数为:cv2.line(img,Point pt1,Point pt2,color,thickness=1,line_type=8 shift=0) 有值的代表有默认值,不用给也行.可以看 ...
- 多线程 or I/O复用select/epoll
1:多线程模型适用于处理短连接,且连接的打开关闭非常频繁的情形,但不适合处理长连接.线程模型默认情况下,在Linux下每个线程会开8M的栈空间,在TCP长连接的情况下,以2000/分钟的请求为例,几乎 ...
- Centos7.3安装和配置jre1.8
在正式环境里 我们可以不安装jdk ,仅仅安装Java运行环境 jre即可: 第一步:下载jre 我们去oracle官方下载下jre http://www.oracle.com/technetwork ...
- 日志、字段备注查询、自增ID联系设置、常用存储过程
-----获取数据字典SQL(表字段说明)SELECT [Table Name] = OBJECT_NAME(c.object_id), [Column Name] = c.name, ...
- API文档管理平台
一.应用场景 在公司中,有很多开发,每个人维护的api接口是不一样的.如果有一个统一的api文档管理平台,每个开发,把自己维护的接口录入进去. 之后再开发别的功能时,不需要重复造轮子,直接调用就可以了 ...
- vue.js学习 自定义过滤器使用(1)
在这个教程中,我们将会通过几个例子,了解和学习VueJs的过滤器.我们参考了一些比较完善的过滤器,比如orderBy 和 filterBy.而且我们可以链式调用过滤器,一个接一个过滤.因此,我们可以定 ...
- 微信小程序蓝牙模块
蓝牙部分知识 关于Service: 每个设备包含有多个Service,每个Service对应一个uuid 关于Characteristic 每个Service包含多个Characteristic,每个 ...
- 自己动手编译OpenSSL库
因为工作需要,要实现一个基于SSL的通信程序.之前没有接触过SSL协议通讯,这次学习了一下如何自己编译OpenSSL库. 我使用的环境是Windows 10 + VS2015 1.首先打开VS2015 ...
- Struts DynaActionForm example
The Struts DynaActionForm class is an interesting feature to let you create a form bean dynamically ...
- .net/c#常用框架/中间件简介
任务调度 Quartz.NET:Quartz.NET是一个开源的作业调度框架,非常适合在平时的工作中,定时轮询数据库同步,定时邮件通知,定时处理数据等. Quartz.NET允 许开发人员根据时间间隔 ...