本篇体验在MVC中使用CKEditor,仅仅算思路、基础,暂没有把验证等与CKEditor结合在一起考虑。
□ 1 使用NUGET引入CKEditor
PM> Install-Package CKEditor
引入后在Scripts中有了CKEditor的相关文件:
![03 03](//images0.cnblogs.com/blog/417212/201403/160306344024655.png)
□ 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; }
}
}
□ 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中如果不设置,也会报如下错:
![01 01](//images0.cnblogs.com/blog/417212/201403/160306348085597.png)
设置允许CKEditor有2种方式:
1、在控制器方法
[ValidateInput(false)]
public ActionResult Create(string subject, string content)
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;
};
控制器与方法:
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
展开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();
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
展开@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>
}
结果:
![02 02](//images0.cnblogs.com/blog/417212/201403/160306353409267.png)
参考资料:
※ ASP.NET MVC 3 使用CKEditor