Thursday, May 13, 2010

CKEditor and MVC

OK. This is a little niche, but in the off-chance someone has the same problem (and the post shows up anywhere in the search results) I thought I would post this.

Using MVC and CKEditor (I had the same problem with FckEditor) I was having trouble posting the results of an editor template using the CKEditor HTML textarea box when using client side jquery validation. This post suggested someone having the same problem, but using PHP and the solution I am using is from a poster Gaby.

Specifically, I am using an editor template to replace a string property decorated with [DataType(DataType.MultilineText)] and [Required]. The CkEditor nicely replaces the text area with the html editor, as expected, but when I submit, the client side library would not recognize that any text had been entered in the html/textarea and would throw an error.

Remove the <% Html.EnableClientValidation(); %> tag and it submits as expected.

The solution was to add a little javascript tag to force the CkEditor instance to update on submit. I also needed to do this without naming the instance, as the Id is set by whatever is passed into the editor template. I also included a loop over CkEditor instance, even though I only have one here I might have an editor template that has multiple in the future, so I left it in.

The full editor template code is below.

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<string>" %>
<script src="<%= Url.Content("~/content/ckeditor/ckeditor.js") %>" type="text/javascript" ></script>

<div class="editor-label">
<%: Html.LabelFor(model => model) %>
     </div>
<div class="editor-field">
     <%: Html.TextAreaFor(model => model, new { @class = "ckeditor" })%>
     <%: Html.ValidationMessageFor(model => model)%>
</div>
<script type="text/javascript">
     $(document).ready(function () {
          $(this).parents('form:first').submit(function () {
               for (instance in CKEDITOR.instances) {
                    CKEDITOR.instances[instance].updateElement();
               }
          });
     });
</script>













2 comments:

  1. I had a similar issue using MVC and Ajax.BeginForm. Ckeditor value was never included in the form collection parameter for the action handling the post. Tried the update as you suggested (using jquery on the submit button click) and worked like a charm. Thank you!

    ReplyDelete
  2. I needed a way of using the editor in MVC3. Your post had my page fully working

    ReplyDelete