Question

I want to use CKEditor with DynamicData Web Site. The all examples that I have found are old version of CKEditor.

So How can I integrate CKEditor with asp.net dyamica data web site?

Any help will be greately appreciated.

İY

Was it helpful?

Solution

What I did was to modify the MultilineText_Edit.ascx file + code-behind located in your Dynamic Data /FieldTemplates/ folder as shown below. Note that in my example you would need to reference jQuery and the CKEditor jQuery adapter, the latter most probably located in /ckeditor/adapters/jquery.js.

The idea is to use the HiddenField control with ID="State" as carrier for the data. Notice the client-script that is registered in the overridden OnPreRender(...): On any .NET form submission (here triggered by Dynamic Data trying to save, update or the like), the data from the CKEditor is saved to the State Hiddenfield, and the data is extraced from the FieldTemplate control from State via the overridden ExtractValues(...).

To clarify: the reason for not returning contents of the TextBox control, Editor, itself, is that this will return the initial contents of the control, discarding CKEditor changes. CKEditor needs to client-side render its markup and stuff to somewhere, and so we do this to the State HiddenField (doing it to the TextBox control itself will mess stuff up, as far as I recall).

One last thing: If you want to keep your MultilineText_Edit.ascx for normal non-CKEditor multiline text editing, put the code in a new file instead, e.g. MultilineHtml_Edit.ascx and set the UIHint for the property to "MultilineHtml" in the metadata class for your partial Linq2SQL class:

[UIHint("MultilineHtml")]
public string Description { get; set; }

MultilineText_Edit.ascx

<%@ Control Language="C#" CodeBehind="MultilineText_Edit.ascx.cs" Inherits="MyProject.DynamicData.MultilineText_EditField" %>


<asp:TextBox ID="Editor" TextMode="MultiLine" runat="server" />
<asp:HiddenField ID="State" runat="server" />

<script type="text/javascript">
    $(document).ready(function () {
        $('#<%= Editor.ClientID %>').ckeditor(function () { }, { height: '400px' });
    });
</script>


<asp:RequiredFieldValidator runat="server" id="RequiredFieldValidator1" CssClass="DDControl DDValidator" ControlToValidate="Editor" Display="Static" Enabled="false" />
<asp:RegularExpressionValidator runat="server" ID="RegularExpressionValidator1" CssClass="DDControl DDValidator" ControlToValidate="Editor" Display="Static" Enabled="false" />
<asp:DynamicValidator runat="server" id="DynamicValidator1" CssClass="DDControl DDValidator" ControlToValidate="Editor" Display="Static" />

MultilineText_Edit.ascx.cs

using System;
using System.Collections.Specialized;
using System.Web.UI;

namespace MyProject.DynamicData
{
    public partial class MultilineText_EditField : System.Web.DynamicData.FieldTemplateUserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Editor.MaxLength = Column.MaxLength;
            Editor.ToolTip = Column.Description;

            SetUpValidator(RequiredFieldValidator1);
            SetUpValidator(RegularExpressionValidator1);
            SetUpValidator(DynamicValidator1);
        }

        public override void DataBind()
        {
            Editor.Text = FieldValueEditString;

            base.DataBind();
        }

        protected override void OnPreRender(EventArgs e)
        {
            Page.ClientScript.RegisterOnSubmitStatement(
                this.GetType(),
                string.Format("kfckpb_{0}", this.ClientID),
                string.Format("$('#{0}').val($('#{1}').val());", State.ClientID, Editor.ClientID)
                );

            base.OnPreRender(e);
        }


        protected override void ExtractValues(IOrderedDictionary dictionary)
        {
            dictionary[Column.Name] = ConvertEditedValue(State.Value);
        }

        public override Control DataControl
        {
            get
            {
                return Editor;
            }
        }

    }
}

OTHER TIPS

My Tested solution

  • Download CKEditor for ASP.NET (ckeditor_aspnet_3.6.2.zip) from http://ckeditor.com/download
  • Purge ckeditor_aspnet_3.6.2.zip to for example c:\temp\ckeditor_aspnet_3.6.2
  • Assuming your MS VisualStudio 2010 WebSite is located here: C:\Users\MyUserName\Documents\Visual Studio 2010\WebSites\MyWebSite\
  • Copy C:\temp\ckeditor_aspnet_3.6.2_Samples\bin\ -folder to ...\MyWebSite\bin\
  • Copy C:\temp\ckeditor_aspnet_3.6.2_Samples\ckeditor\ -folder to ...\MyWebSite\ckeditor\
  • In VisualStudio, add Reference to the CKEditor:
    • In Solution Explorer right-click ...\MyWebSite\ and choose Add Reference :
    • Click Browse -pane, browse to ...\MyWebSite\bin\CKEditor.NET.dll and click OK
  • Create these files and save them to ...\MyWebSite\DynamicData\FieldTemplates\

Comments and suggestions are welcome.

...\MyWebSite\DynamicData\FieldTemplates\CKEditor_edit.ascx

<%@ Control Language="C#"
    AutoEventWireup="true"
    CodeFile="CKEditor_Edit.ascx.cs"
    Inherits="Html_EditField" %>
<%@ Register Assembly="CKEditor.NET" Namespace="CKEditor.NET" TagPrefix="CKEditor" %>

<CKEditor:CKEditorControl 
    ID="TextBox1"
    Text='<%# FieldValueEditString %>'
    runat="server"
    Width="800"
    PasteFromWordNumberedHeadingToList="True"
    PasteFromWordPromptCleanup="True"
    PasteFromWordRemoveFontStyles="True"
    PasteFromWordRemoveStyles="True"
    Toolbar="[['Bold', 'Italic', '-', 'NumberedList','BulletedList', '-', 'Link', 'Unlink', '-', 'About'],['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'SpellChecker', 'Source'],['Undo', 'Redo', '-', 'Find', 'Replace', '-', 'SelectAll', 'RemoveFormat']]">
</CKEditor:CKEditorControl>

...\MyWebSite\DynamicData\FieldTemplates\CKEditor_edit.ascx.cs

using System;
using System.Collections.Specialized;
using System.Web.UI;

public partial class Html_EditField : System.Web.DynamicData.FieldTemplateUserControl
{
    //refer http://www.graytechnology.com/Blog/post/Using-a-Rich-Text-Editor-with-Dynamic-Data.aspx for explanation
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected override void ExtractValues(IOrderedDictionary dictionary)
    {
        dictionary[Column.Name] = ConvertEditedValue(TextBox1.Text);
    }

    public override Control DataControl
    {
        get 
        {
            return TextBox1;
        }
    } 
}

...\MyWebSite\App_Code\mytable.cs ##

using System;
using System.ComponentModel.DataAnnotations;
using System.Web;
using System.ComponentModel;

/// <summary>
/// Formatting the mytable -table fields.
/// </summary>

[MetadataType(typeof(mytableMetadata))]
public partial class mytable
{
    // The CKEditor cannot check the length of myfield, and the 
    // DataAnnotations StringLengthAttribute doesn't work with CKEditor,
    // so you have to do a custom check. 
    // 
    // This works as expected only when NOT debugging. 
    // 
    // In debug mode the application will open a window saying 
    // "ValidationException was unhandled by user code",
    // but the message is shown as it is set below in the code. 
    // Hit F5 again, and application will continue OK.
    partial void OnValidate(System.Data.Linq.ChangeAction action)
    {
        if (this._myfield.Length > 1024)
        {
            throw new ValidationException(
               "Length of myfield must be less than 1025 characters.");
        }    }

public class mytableMetadata
{
    [DisplayFormat(HtmlEncode = false)]  // The field is displayed as HTML, when not edited. 
    [UIHint("CKEditor")]                 // The field is edited with CKEditor. 
    public object myfield { get; set; }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top