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篇将会侧重于专题的讲解,一篇文章解决一个实际问题. 根据园友的反馈, 本篇文章将会先对呼声最高的仓储模式进行讲解. 文 ...
随机推荐
- javaweb笔记一
内连接(自然连接): 只有两个表相匹配的行才能在结果集中出现 外连接: 包括 (1)左外连接(左边的表不加限制) (2)右外连接(右边的表不加限制) (3)全外连接(左右两表都不加限制 一个空的构造器 ...
- new Function和eval区别
eval和new Function都可以动态解析和执行字符串.但是它们对解析内容的运行环境判定不同. eval中的代码执行时的作用域为当前作用域.它可以访问到函数中的局部变量. new Functio ...
- 解决insert语句插入时,需要写列值的问题
今天发现解决这个问题其实很简单,闲话不多谈,我直接附上语句 ) select @s = isnull(@s+',', '') + [name] from syscolumns where id = o ...
- c++实现二叉树的非递归创建以及非递归先序、中序、后序遍历
二叉树的创建 思路:数组中从上到下依次放着二叉树中的元素,使用递归很容易实现,那么这里使用容器来存放之前的状态实现循环创建二叉树. TreeNode* createTree(int *arr, int ...
- Chrome-Adobe Flash 无法正常使用
https://support.google.com/chrome/answer/6258784 该网站因是是google.com,被强了,所以一般打不开. 故将google官方说明记录以下: 如果 ...
- gym 100531 三维几何+搜索
精度有点毒, 其实可以不用double, 因为A, B必定在其中一个在三角形上,可以投影到只有x,y轴的地方叉积比较. #include<bits/stdc++.h> #define LL ...
- TestNG入门到...
目录 一.概述 二.@Test注解常用参数 三.测试中常用的断言(assert) 四.TestNG常用注解及使用 五.配置文件xml常用标签 六.参数传递 七.测试报告 一.概述 1.TestNG是一 ...
- mysql 存储过程详解
MySQL 存储过程是从 MySQL 5.0 开始增加的新功能.存储过程的优点有一箩筐.不过最主要的还是执行效率和SQL 代码封装.特别是 SQL 代码封装功能,如果没有存储过程,在外部程序访问数据库 ...
- [js]正则篇
一.正则基本概念 1.一种规则.模式.文本处理工具 2.强大的字符串匹配工具 3.在js中常与字符串函数配合使用 二.js正则写法 正则在js中以正则对象存在: (1)var re=new RegEx ...
- Java异常处理中的恢复模型
异常处理理论上有两种基本模型.Java支持终止模型,在这种模型中,假设错误非常关键,以至于程序无法返回到异常发生的地方继续执行.一旦异常被抛出,就表明错误已无法挽回,也不能回来继续执行.长久以来,尽管 ...