Pages

Sunday, July 22, 2012

How to implement CKEditor in MVC3 and the Razor Engine

The FCK Editor became the CK Editor, I guess they opted to drop the F over adding a U.
Step 1  : Change to Text Area
You should  have something like this in your Create and Edit Views
@Html.EditorFor(model => model.Text)
Lets change that to :
@Html.TextAreaFor(model => model.Text, new { @class = “adminRichText” })
Step 2 : Widen the text area
In your Site.Css file add the folowing to widen the text area :
.adminRichText
{
width:450px;
}
Step 3 : Add the CK Editor (formerly FCK Editor) to your project
a. Download here
b. Create a ‘Javascript’ folder under ‘Content’ in your website.
c. Extract to /Javascript/Content.
Step 4 : Include the scripts in your View
Below the validation scripts add
<script type=”text/javascript” src=”@Url.Content(“~/content/javascript/ckeditor/ckeditor.js”)”></script>
<script type=”text/javascript” src=”@Url.Content(“~/content/javascript/ckeditor/adapters/jquery.js”)”></script>
Step 5 : Turn the text area into a Rich Text Box
At bottom of view after controls are initialized add:
<script language=”javascript” type=”text/javascript”>
jQuery(“.adminRichText”).ckeditor();
</script>
Step 6 : Enable Post Back of Rich Text for your Edit and Create Methods in your controller class

[HttpPost, ValidateInput(false)]
public ActionResult Create(AreaText areaText)
[HttpPost, ValidateInput(false)]
public ActionResult Edit(string id, FormCollection collection)
Step 7: Use Html.Raw to display the data
On your index view update the output area to decode the html.
item.Text
becomes
@Html.Raw(item.Text)


You can done this using following setting :

“In your CKEditor config file add the following line:
config.htmlEncodeOutput = true;”