Rich Text Editing with CKEditor, MVC 3 and the Razor Engine


I was creating a model /view for editing large chunks of text on my website with MVC and the Razor engine. I created everything following Sott Gu’s tutorial on how to build a music store. When all was said and done I had a 50 character wide single line textbox for editing a large html block and thought ok this isn’t I deal.  Here are the steps I took to get a rich text editor in there.

Most of this came from this post on code project but it’s a bit outdated and doesn’t have everything.

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)

ckEditor in mvc

ckEditor in mvc

Note : There are some good suggestions in the comments on ways to continue using validation :

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

Option 2 from Blair.
“I was able to get this to work without having to turn off validation by putting in
[AllowHtml] in the property definition”

Advertisements

About Kevin Buckley
.Net web developer with a lot of experience in CMS. Currently working at Sitecore as Solutions Engineer.

26 Responses to Rich Text Editing with CKEditor, MVC 3 and the Razor Engine

  1. vge says:

    Thank you for your post…
    Just a little question : on create view it’s necessary to press two time to submit the form, it’s normal ?

    • That seems to be a problem with having a validator, I took the validation off of the model and did it server side after I noticed that happening.

      • vge says:

        Yes I have attribute [Required] on this field in my model. I remove this attribute and ok it’s work..
        Thank you.

  2. goran says:

    Hi, and thanks for this.
    I have one question for http post action create in mvc3, i have application that create articles (news) in database, so my controller is like:
    [HttpPost]
    public ActionResult Create(Article article)
    {
    if (ModelState.IsValid)
    {
    databaseDB.Articles.Add(article);
    databaseDB.SaveChanges();

    return RedirectToAction(“Index”);
    }

    return View(article);

    }

    so i have text area for in my aricle, how to save it in database after editing with ckeditor?

    • at the least you need set input validation to false with an attribute. Here is what my code looks like.

      [HttpPost, ValidateInput(false)]
      public ActionResult Create(AreaText areaText)
      {

      try
      {
      // TODO: Add insert logic here
      areaText.Area = Sanitizer.GetSafeHtmlFragment(areaText.Area);
      areaText.Text = Sanitizer.GetSafeHtmlFragment(areaText.Text);
      mhgDb.AreaTexts.Add(areaText);
      mhgDb.SaveChanges();
      return RedirectToAction(“Index”);
      }
      catch
      {
      return View();
      }

      }

  3. goran says:

    Hi, thanks for reply.
    I tried everything following your steps, i just can’get text editor to show.
    I put textarefor and download ckeditor but nothing

    For working corectly I nedd only ckeditor.js and adapters/jquery.js?? or everythnig from folder ckeditor?

    • Bruce Patin says:

      The statement that makes it show is:
      jQuery(“.adminRichText”).ckeditor();

      Make sure that you use the same CSS classname everywhere, as in the example. I used a different classname, but made sure that it was used everywhere.

      Also, I needed to retype to fix all of the quote characters in the example to get it to work. Cutting and pasting from this web page resulted in the wrong double quote character, intended for word processing, not programming.

      This is by far the cleanest to implement rich text editor I have tried so far!

  4. You need everything in that folder to exist.

    Maybe try FireBug for Firefox and see if you are getting a javascript error.

  5. Frantisek Fiala says:

    Hi, thanks for your post.
    I have one question:
    it is possible somehow to automatize rich text field editing in the class definition using dataanotation [DataType(…)]?

    I woluld like to use then: @Html.EditorForModel() in the view to generate richtext ckeditor field automatically.

    And how to use it in the viewing only views? Is it possible?

    Thank you

  6. Michael says:

    You can tell CKEditor to html encode its output to avoid the need to turn off input validation in the controller for the entire model object. If your form has other fields that don’t use a rich text editor, then you would likely still want these fields validated.

    In your CKEditor config file add the following line:

    config.htmlEncodeOutput = true;

    This way html encoded text will be passed to the controller, the asp.net input validation will pass successfully, and you can then store the html encoded text in your database.

    When editing this value later, CKEditor will know automatically decode the html encoded text for editing.

    And when you want to render this text as html to a page for viewing, instead of calling

    @Html.Raw(Model.SomeTextField)

    you can call

    @Html.Raw(HttpUtility.HtmlDecode(Model.SomeTextField))

    Regards,
    Michael.

  7. Blair says:

    I was able to get this to work without having to turn off validation by putting in
    [AllowHtml] in the property definition,
    so for example
    [AllowHtml]
    public String PageContent
    {
    get;
    set;
    }

    It’s working perfectly unless I’m missing something

  8. angel88 says:

    I’m having the same error:
    I need to press 2 times the Submit button and I already added [Allow html] to my field and I tried with config.htmlEncodeOutput = true; in my CKEditor.config but doesn’t work correct.
    Only If I remove the [Required] dataannotation works.
    If you have another solution, please tell me.

  9. Harry says:

    Thanks a lot for this very helping post!
    Also many thanks to Michael!
    This Helped me in my first mvc 3 project!

  10. jfbouz says:

    Mr. Buckley. Thank you for this post. After Googling for hours on this subject, this was easily the most concise and effective implementation of the RTE for MVC I’ve seen. Worked like a charm right from the start.
    Thanks!
    Jim

  11. Ben says:

    Awesome work mate.

    Worked a treat

  12. Thank you a lot for sharing this with all folks you really understand what you are talking about! Bookmarked. Please additionally talk over with my website =). We can have a link trade agreement between us

  13. grasshopper says:

    How did you get around the 4000 character limit? I’m doing something similar, but I am unable to save Rich Text that is longer than 4000 characters.

  14. Baba Ana says:

    Thank you very much for the very clear, concise and extremely useful article. I implemented the CKEditor in a few minutes and it works great.

    I’d like to know, how to manually add (new lines) between paragraphs in the rich text box? I need this because in my application I convert the text to PDF and that one simply ignores the   inserted by CKEditor when pressing Enter.

    Thank you!

    • Baba Ana says:

      I found the answer: it is necessary to configure CKEDITOR.config.enterMode and/ or CKEDITOR.config.shiftEnterMode as needed.

  15. Mahendra Duwal says:

    Hi, I am new to mvc3 and using ckeditor for the first time in it. The problem is ckeditor works fine with any normal view page but when I tried it to render a textarea in ajax modal popup in mvc3, i’m not getting ckeditor. Could you please get me any advice on how to use it in ajax popup in mvc3? Anyway thanks for the great tutorial.

  16. Poe says:

    I like your post.It help me.Thz

  17. Rui says:

    Hi.
    Everything works fine, but I just can’t seem to find AreaText.
    Rui Martins

  18. AreaText is just the Sample place I was using to store the Data.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: