Easy way to get FCKEditor to work inside an ASP.Net AJAX UpdatePanel

The Problem

I had a MultiLine TextBox inside an UpdatePanel and I wanted that TextBox to have rich editing capabilities so I chose FCKEditor. But, now when I do a partial PostBack, the TextBox doesnt retain it value.

An Initial Solution

So, I searched for a solution to this problem and found this post, but it seemed like more of a hack than I prefer.

A More Elegant Solution

As it turns out, there is a much simpler way hinted at in the FCKEditor wiki:

private void Page_Load(object sender, EventArgs args)
{
    Page.ClientScript.RegisterOnSubmitStatement(
        editor.GetType(),
        "editor",
        "FCKeditorAPI.GetInstance('" + editor.ClientID + "').UpdateLinkedField();");
}

If you have multiple FCKEditors, you need to apply this solution to each one:

private void Page_Load(object sender, EventArgs args)
{
    Page.ClientScript.RegisterOnSubmitStatement(
        editor1.GetType(),
        "editor1",
        "FCKeditorAPI.GetInstance('" + editor1.ClientID + "').UpdateLinkedField();");

    Page.ClientScript.RegisterOnSubmitStatement(
        editor2.GetType(),
        "editor2",
        "FCKeditorAPI.GetInstance('" + editor2.ClientID + "').UpdateLinkedField();");
}

One Small Problem

There is one small issue with this solution, however—there will be JavaScript errors if you hide the TextBox during a partial PostBack.

For example, if you have a three step form: edit, review, and then publish. On the edit step the TextBox is shown and you enter and style your rich text, then you click the review button and this causes a partial PostBack which removed the TextBox and shows a preview of the text you enterred. When you click the publish button there will be a JavaScript error because the Textbox is no longer visible.

The Final Solution

To solve this problem and come to an elegant, working solution I just needed to add in some basic error checking. Since the JavaScript was getting a little more complex, I decided to move the main work into a .js file:

function FCKUpdateLinkedField(id)
{
    try
    {
        if(typeof(FCKeditorAPI) == "object")
        {
            FCKeditorAPI.GetInstance(id).UpdateLinkedField();
        }
    }
    catch(err)
    {
    }
}

And the page code now looks like:

private void Page_Load(object sender, EventArgs args)
{
    Page.ClientScript.RegisterOnSubmitStatement(
        editor.GetType(),
        "editor",
        "FCKUpdateLinkedField('" + editor.ClientID + "');");
}

Bookmark the permalink. Follow any comments here with the RSS feed for this post. Post a comment or leave a trackback: Trackback URL.

One Comment

  1. Nameer
    Posted July 27, 2008 at 1:38 am | Permalink

    Still get FCK is not defined if you postback for the second time (in firfox not ie)

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*