一、原生方法:

在 razor 中 使用Fckeditor 编辑内容,需要引入js

<script src="@Url.Content("~/fckeditor/fckeditor.js")" type="text/javascript"></script>

至于html编码


          <tr>
            <td>内容</td>
            <td>
                @Html.HiddenFor(model => model.Content)
                <script type="text/javascript">
                    var f = new FCKeditor("FckContent", "628", "445");
                    f.Create();
                </script>
                @Html.ValidationMessageFor(model => model.Content, "", new { @class = "red" })
            </td>
          </tr>

要把Content中的数据传到后台,需要在提交时间中把值赋予@Html.HiddenFor(model => model.Content)

<input type="image" src="/images/confirm.jpg" alt="确认" onclick="getEditorHTMLContents('FckContent')" />

js 方法如下


function getEditorHTMLContents(EditorName) {
        var otxt = FCKeditorAPI.GetInstance(EditorName).GetHTML(true);
        if (otxt == '' || otxt == null) {
            return false;
        }
        else {
            $('input[id$="Content"]').val(otxt);
            return true;
        }
    }

这样后台中传入的model中包含Content

二、封装到MVCHelper

This post describes a set of HTML Helpers I've written for use in an ASP.NETMVC 3 web site project, which enable you to insert a CKEditor instance with no more effort than this:

@Html.CKEditorHeaderScripts()
...
@Html.CKEditorFor(model => model.Body)
...
<input type="submit" value="Save"
 onclick="@Html.CKEditorSubmitButtonUpdateFunction()" />

This solution requires jQuery, CKEditor3, and the jQuery adapter which comes with CKEditor. It enables client-side validation to work with the editor via the helper used in the onclick handler of the submit button. It works with both Razor and WebForms view engines, and includes all of the strong-typed Html Helpers you would expect, and almost all of the weak typed ones as well. Read on to see how to use it, and download it for use in your projects.

Usage of CKEditor HTML Helpers for MVC

Once you have included the single source file, enabled jQuery for the project, and have the standard client-side code that is injected into MVC3 editor views, you simply use the following helper once per view to enable the plumbing needed. I put it right after the two validation-related jQuery scripts:

<script src="/Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
@Html.CKEditorHeaderScripts()

That helper simply outputs the CKEditor scripts required, and defines a javascript function which callsupdateElement() on all CKEditor instances before client-side validation is done. Then, you use the various overloads of CKEditor()/CKEditorFor() to output your actual CKEditor instances. These helpers are based directly on MVC3's TextArea()/TextAreaFor() helpers, and will output essentially the same HTML as those helpers, meaning non-Javascript browsers will simply see normal textareas. Once the helper has rendered the textarea output, it then adds a jQuery call to initialize a CKEditor instance, add a special CSS class, and allows you to define your own CKEditor config/callback information.

Following are some helper calls you could do with this:

@Html.CKEditor("Body", (string)ViewBag.BodyText, "toolbar:'Basic'", new{cols=20, rows=5})
@Html.CKEditorFor(model => model.Body, rows: 5, columns: 40);
@Html.CKEditorFor(model => model.Body, "uiColor:'#996611'")
@Html.CKEditorFor(model => model.Body)

The pattern of the overloads defined is very similar to those for TextArea/TextAreaFor, with the addition of the string parameter ckEditorConfig. In the case of the weak-typed CKEditor() methods, you must define the value parameter for all overloads. Beyond that, all of the overloads you would expect will exist.

Finally, to enable client-side validation upon submission of the form which contains one or more CKEditor instances, a helper method is defined which calls a Javascript function that was injected previously. That function uses the CSS class added as a jQuery selector to call the CKEditor updateElement() method on each one. Without doing this, a CKEditor for a model field with the data annotations 'Required' attribute would falsely be indicated as being empty the first time you click to submit the form.

<input type="submit" value="Save"
 onclick="@Html.CKEditorSubmitButtonUpdateFunction()" />

Caveats for Usage

The non-typed CKEditor() helpers all require you to specify a value, except for the most simplified one. You may simply provide the empty string if you like. This was due to the complexities that would have ensued from trying to provide extra overloads with the ckEditorConfig parameters I was adding.

If you provide a ckEditorConfig value, you should do so in javascript config syntax, as a literal string (eg@Html.CKEditorFor(model=>model.Data, "{toolbar: 'Basic', uiColor: 'Red'}")). The helpers will provide the surrounding squiggly brackets if you forget them. Doing so will override the height and widthconfig values that the helpers normally set themselves. You can use a custom config file, or the CKEditor standard config file to set default values, including sizes, to make using instance-specific config information simpler.

CKEditor HTML Helpers Installation and Configuration

First, download this zip. It contains a single .cs file, which is the full source code for the helpers:

CKEditorHelpers.zip

Unzip the CKEditorHelpers.cs file and add it to your MVC project wherever seems appropriate. Then open the file, and investigate the few items at the top which may need alteration:

/* The following values should be configured to your application/desires. */
/// The CSS Class for CKEditor instances, for internal use by these helpers
private const string CK_Ed_Class = "ckEditorBoxGen";
/// The virtual, rooted directory where CKEditor can be found.
///Should include trailing slash. eg /CKEditor/
private const string CK_Ed_Location = "/CKEditor/";
/// The default rows of textarea/em height of CKEditor
private const int DefaultTextAreaRows = 20;
/// The default columns of textarea/em width of CKEditor
private const int DefaultTextAreaColumns = 40;

These should all be pretty self-explanatory. The CK_Ed_Class need not be altered unless you think it will conflict with a CSS class you have elsewhere. The default text area sizes will be set as style properties on the textarea tag in em units, and sent to the CKEditor instance as height and width in em units. Note that the textarea size on browsers without Javascript likely will not be exactly the same as the CKEditor box would be, but they will be close. You can override these textarea values in the helper's overloads, and you can also set CKEditor config values with the proper overloads. You could do both if you wish to fine-tune the sizes so that they match exactly with or without the javascript editor.

You needn't read on if you merely wish to use the helpers; that should cover everything you need. Feel free to leave comments here or use the 'Contact' page on this site if you have questions, comments or recommendations.

Examining the Source Code of the CKEditor HTML Helpers

I started developing these helpers from the source code of ASP.NET MVC3 RTM's TextAreaExtensions.csfile. Therefore, most of the internal conventions for Html helpers will have been applied for the CKEditor helpers, too. The bulk of the code is the various overloads of CKEditor()/CKEditorFor(); I have surrounded those with regions to make it easier to explore the code. In the "Related HTML Helpers" region are the two other helpers; the one that sets up the 'header' scripts (which do not necessarily need to be in the HTML head) and the one that outputs the call to trigger the update function. Both merely output short bits of javascript.

public static MvcHtmlString CKEditorHeaderScripts(this HtmlHelper help) {
return MvcHtmlString.Create(@"
<script src=""" + CK_Ed_Location + @"ckeditor.js"" type=""text/javascript""></script>
<script src=""" + CK_Ed_Location + @"adapters/jquery.js"" type=""text/javascript""></script>
<script type=""text/javascript"">
 function UpdateCKEditors() { $('." + CK_Ed_Class + @"').ckeditorGet().updateElement(); }
</script> ");
}

As you can see, it is using some of the constants defined at the top to include the CKEditor script and jQuery adapter. Alter these if you need to. It also defines a function which will be used to call theupdateElement() CKEditor function on all of the CKEditor instances created by the helpers. This function updates the underlying DOM with the data for the textarea so that validators which run before the POST happens will see the correct information. So, then we have this:

public static MvcHtmlString CKEditorSubmitButtonUpdateFunction(this HtmlHelper help) {
return MvcHtmlString.Create("javascript:UpdateCKEditors()");
}

This is merely a convenience for the sake of Intellisense support, to be added to the onclick event of the form's submit button, or in another appropriate location to be called before the validators would fire. You could of course simply call the UpdateCKEditors() javascript function in any other way you would like.

The meat-and-drink of the main array of helpers is a private method to which they all eventually delegate,CKEditorHelper(). This method builds the underlying textarea tag in almost exactly the same way as the MVC3 built-in TextAreaHelpers.cs source code does. The difference is that it uses styles to define the size of the textarea rather than the cols and rows attributes, to better match the sizes of the textarea to the javascript-enabled CKEditor.

Of key importance to note here is that since I use the same code that Microsoft did to build the textarea, it should work exactly as you would expect any other helper form control. For example, if you use prefixes for field names. After the textarea is built up, the script tag which enables the CKEditor is then also created:

TagBuilder scriptBuilder = new TagBuilder("script");
scriptBuilder.MergeAttribute("type", "text/javascript");
if (string.IsNullOrEmpty(ckEditorConfigOptions)) {
ckEditorConfigOptions =
string.Format("{{ width:'{0}em', height:'{1}em' }}",
 rowsAndColumns["cols"], rowsAndColumns["rows"]
);
}
if (!ckEditorConfigOptions.Trim().StartsWith("{"))
 ckEditorConfigOptions = "{" + ckEditorConfigOptions;
if (!ckEditorConfigOptions.Trim().EndsWith("}"))
 ckEditorConfigOptions += "}";
scriptBuilder.InnerHtml = string.Format(" $('#{0}').ckeditor({1}).addClass('{2}'); ",
fullName,
ckEditorConfigOptions,
CK_Ed_Class
);

You can see where I set the CKEditor config options for the width and height based on the 'rols' and 'rows' info, unless you have provided your own configuration information. This code could be improved to parse the supplied config info, and add in the width and height items each only if that item was not already supplied. Finally, the curly braces are added if they weren't supplied already, then the jQuery call which creates the CKEditor and adds the custom CSS class is written. The textarea and script elements are concatenated and output, and that's it!

Conclusion and What's Coming

Hopefully, this is helpful to someone. As simple as CKEditor is to integrate into a web site, this makes it that much easier with ASP.NET MVC3. Please feel free to comment or contact me if you have any questions, comments or ideas for improvement.

If you missed it above, here is the source download link: CKEditorHelpers.zip

Coming up, I will post my solution to use the old file browser/uploader from FCKEdit with CKEditor, and how I integrated that with ASP.NET MVC, as well.

CKEditor Html Helpers for ASP.NET MVC3 Razor/WebForms Views的更多相关文章

  1. ASP.NET MVC3 Razor 调试与预加载

    目录(?)[-] 获取服务器信息 FormsAuthenticationSlidingExpiration 属性 MVC3预加载   在ASP.NET MVC3开发中,调试中怎么也是不可缺少的,那对于 ...

  2. ASP.NET MVC3 Razor视图引擎-基础语法

    I:ASP.NET MVC3在Visual Studio 2010中的变化 在VS2010中新建一个MVC3项目可以看出与以往的MVC2发生了很明显的变化. 1.ASP.NET MVC3必要的运行环境 ...

  3. (转)ASP.NET MVC3 Razor视图引擎-基础语法

    转自:http://kb.cnblogs.com/page/96883/ I:ASP.NET MVC3在Visual Studio 2010中的变化 在VS2010中新建一个MVC3项目可以看出与以往 ...

  4. 将 ASP.NET MVC3 Razor 项目部署到虚拟主机中

    国内很多网站空间都只支持.NET 2.0 和 .NET 3.0 3.5,很少有空间商支持.NET 4的,即使有个别支持.NET 4,但是不支持MVC的默认路由访问形式. Go Daddy 的主机支持, ...

  5. [转]]将 ASP.NET MVC3 Razor 项目部署到虚拟主机中

    原链接:http://www.cnblogs.com/taven/archive/2011/08/14/2138077.html 国内很多网站空间都只支持.NET 2.0 和 .NET 3.0 3.5 ...

  6. ASP.NET MVC3 Razor 初心者容易遇到的問題(转)

    这是一些相关的文章地址 http://demo.tc/Post/679 http://blog.csdn.net/cheny_com/article/details/6298496

  7. ASP.NET MVC3 系列教程 - Razor视图引擎基础语法

    http://www.cnblogs.com/highend/archive/2011/04/09/aspnet_mvc3_razor_engine.html 4. 关于所有带"_" ...

  8. 一步步学习ASP.NET MVC3 (3)——Razor(1)

    请注明转载地址:http://www.cnblogs.com/arhat 首先这个<一步步学习ASP.NET MVC3>前段时间有些忙,没有顾得上写文章,昨天呢写了3个和ASP.NET的相 ...

  9. 在没有安装有mvc3的主机上部署asp.net mvc3网站,需要包含的DLL文件

    原文:在没有安装有mvc3的主机上部署asp.net mvc3网站,需要包含的DLL文件 http://hi.baidu.com/aspxdiyer/blog/item/5515a69943232f1 ...

随机推荐

  1. 工具fiddler学习

    1:Fiddler 是以代理web服务器的形式工作的,它使用代理地址:127.0.0.1, 端口:8888. 当Fiddler会自动设置代理.能支持HTTP代理的任意程序的数据包都能被Fiddler嗅 ...

  2. svn+ssh方式svn服务器和客户端的配置[转载]

    本文摘自:http://hi.baidu.com/farmerluo/item/e7d9d72d098afc0a42634abb 我们最近一个项目用的那几台服务器都是客户给的,但是管理非常严格,只给我 ...

  3. 领域模型驱动设计(Domain Driven Design)入门概述

    软件开发要干什么: 反映真实世界要自动化的业务流程 解决现实问题 领域Domain Domain特指软件关注的领域 在不能充分了解业务领域的情况下是不可能做出一个好的软件 领域建模 领域模型驱动设计 ...

  4. Hyper-v虚拟机文件VHDX与VHD的格式转换

    今天遇到一个坑,我在本机(windows 10)上创建的CentOS虚拟机作为docker的宿主机,部署了gitlab等容器,准备迁移到服务器上的时候,发现始终无法导入,提示必须通过Hyper-v导出 ...

  5. windows环境下安装win8.1+Mac OS X 10.10双系统教程

    首先要感谢远景论坛里的各位大神们的帖子  没有他们的分享我也不能顺利的装上Mac OS X 10.10! 写这篇随笔主要是为了防止自己遗忘,同时给大家分享下我的经验. 本教程适用于BIOS+MBR分区 ...

  6. 网页中插入FLASH(swf文件)的html代码

    一.简单插入flash图像<embed src="你的flash地址.swf"width="300" height="220"> ...

  7. Windows 安装 openssl

    http://slproweb.com/products/Win32OpenSSL.html File Type Description Win32 OpenSSL v1.1.0b Light 3MB ...

  8. android开发学习之Level List篇

    Level List google 说明:A Drawable that manages a number of alternate Drawables, each assigned a maximu ...

  9. .NET相关操作其他文件的小程序(系列文章)

    平时自诩为使用.NET做开发,但是实际上从一开始学习C#直到现在除了做个几个不登大雅之堂的小网站,做过几个winform程序和几个控制台应用程序,真的没有踏踏实实地用.NET开发过某些属于自己的东西. ...

  10. ABP入门系列(4)——领域层定义仓储并实现

    一.先来介绍下仓储 仓储(Repository): 仓储用来操作数据库进行数据存取.仓储接口在领域层定义,而仓储的实现类应该写在基础设施层. 在ABP中,仓储类要实现IRepository接口,接口定 ...