How to use CKEditor in ASP.NET Web Forms [download codes]

How to use CKEditor in ASP.NET Web Forms [download codes]

Sometimes you need to provide a feature to add HTML contents in a database table’s column. For creating this feature you can use CKEditor which is a free HTML Text Editor. It’s integration is fairly simple and this tutorial will teach how to use CKEditor in your ASP.NET Web Forms website.

I have also written the same tutorial for ASP.NET MVC application. So if your site is in MVC then check how to use CKEditor on ASP.NET MVC.

There are just 3 steps for using CKEditor in your website:

Step 1: Download and Add it to your website’s Folder

Download CKEditor from here and then extract all it’s files to your website’s folder.

Step 2: Add Reference to ckeditor.js file

Add the reference to ckeditor.js file in your web page’s head area like shown below:

<script src="ckeditor/ckeditor.js"></script>

Step 3: Add CKEditor Script

The work of the CKEditor script is to hide the Text Area and show an HTML Editor in it’s place. So you first create a text box with attribute TextMode=”MultiLine”, and then use CKEditor Script to do the hiding part.

<asp:TextBox ID="descriptionTextBox" runat="server" TextMode="MultiLine"></asp:TextBox>
<script type="text/javascript" lang="javascript">CKEDITOR.replace('<%=descriptionTextBox.ClientID%>');</script> 

Example: Use CKEditor in Web Page

Let us now create a web page and use CKEditor in it. In this web page user will be able to write HTML contents in CKEditor, which will be stored in the Database, on the click of the button.

User will also be able to edit this content by fetching the stored content from the Database and showing it in the CKEditor.

Code on .ASPX Page

I will have 2 controls on my web page, for – Name & Description. ‘Name’ will be a text box while ‘Description’ will be text area.

I will create the description text area by making it a text box with TextMode attribute as MultiLine.

<div id="errorDiv" runat="server" class="validationDiv"></div>
    <div id="studentFormDiv" class="studentForm" runat="server">
        <table>
            <tbody>
                <tr>
                    <td>
                        <label>Name</label>
                        <asp:TextBox ID="nameTextBox" runat="server"></asp:TextBox>
                        <span id="nameSpan"></span>
                    </td>
                </tr>
                <tr>
                    <td>
                        <label>Description</label>
                        <asp:TextBox ID="descriptionTextBox" runat="server" TextMode="MultiLine"></asp:TextBox>
                        <script type="text/javascript" lang="javascript">
                            CKEDITOR.replace('<%=descriptionTextBox.ClientID%>');
                        </script>
                        <span id="descriptionSpan"></span>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Button ID="submitButton" runat="server" Text="Submit" OnClick="submitButton_Click" />
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
    <div id="studentDataDiv" runat="server" class="studentForm"></div>
    <asp:Button ID="editButton" runat="server" Text="Edit" OnClick="editButton_Click" Visible="false"/>

Explanation:

  • The errorDiv is where the validation errors will be shown. I will use jQuery to validate the text box and text area so that user has to fill something on both of them before submitting.
  • These 2 controls are shown inside an html table. The submitButton click event will be the place where the ‘insert to database codes’ will be written.
  • There is also another div called studentDataDiv which will show the values of the text box and text area that is submitted by the user.
  • An edit button called editButton given below will fetch the database values, and show it on the name text and description text area.
Add jQuery Validation Code

The jQuery validation will force user to insert some text on the controls before they can be submitted. Add this code just before the ending body tag of your web page.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        $("#<%=submitButton.ClientID %>").click(function () {
            CKEDITOR.instances["<%= descriptionTextBox.ClientID %>"].updateElement();                                    

            return Validate();
        });

        function Validate() {
            var errorMessage = "";

            //Name
            if ($("#<%=nameTextBox.ClientID %>").val() == "")
                errorMessage += "Enter Name<br/>";
            //End

            //Description
            if ($("#<%=descriptionTextBox.ClientID %>").val() == "")
                errorMessage += "Enter Description";
            //End

            if (errorMessage.length == 0)
                return true;
            else {
                $("#<%=errorDiv.ClientID %>").html(errorMessage);
                return false;
            }
        }
    });
</script>

  • It will be worth mentioning that on the first line I have called CKEditor’s updateElement() method.
  • This method will update the descriptionTextBox by putting all the contents of CKEditor into it.
  • This is necessary because we are actually validating the text area and not the CKEditor itself (remember that CKEditor hides the text area).
  • Note – Make sure to add ValidateRequest=”false” on your page directive else you will get a message that says – A potentially dangerous Request.Form value was detected from the client.
Code on .ASPX.CS Page

Add the below code in the .aspx.cs page:

protected void submitButton_Click(object sender, EventArgs e)
{
    if (Validation())
    {
        MyStruct myStruct;
        myStruct.name = nameTextBox.Text;
        myStruct.description = descriptionTextBox.Text;
        Session["MySession"] = myStruct;
        BindDataTable();
    }
}

Boolean Validation()
{
    var errorMessage = "";

    //Name
    if (nameTextBox.Text == "")
        errorMessage += "Enter Name<br/>";
    //End

    //Description
    if (descriptionTextBox.Text == "")
        errorMessage += "Enter Description";
    //End

    if (errorMessage.Length == 0)
        return true;
    else
    {
        errorDiv.InnerHtml = errorMessage;
        return false;
    }
}

void BindDataTable()
{
    string table = "<table>";
    table += "<tr><td class=\"red\">Name: </td></tr><tr><td>" + ((MyStruct)Session["MySession"]).name + "</td></tr>";
    table += "<tr><td class=\"red\">Description: </td></tr><tr><td>" + ((MyStruct)Session["MySession"]).description + "</td></tr>";
    table += "</table>";
    studentDataDiv.InnerHtml = table;

    studentFormDiv.Visible = false;
    editButton.Visible = studentDataDiv.Visible = true;
}

protected void editButton_Click(object sender, EventArgs e)
{
    nameTextBox.Text = ((MyStruct)Session["MySession"]).name;
    descriptionTextBox.Text = ((MyStruct)Session["MySession"]).description;

    studentFormDiv.Visible = true;
    editButton.Visible = studentDataDiv.Visible = false;
}

Explanation: On the submit button’s click, I am creating a Struct object and storing the values of the name and description in it. This Struct’s value is stored in a Session variable.

I just used Session here but you can also use Database instead of session.

To get the values from CKEditor simple use:

string desValue = descriptionTextBox.Text;

  • The Validation() function does the server side validation of these 2 controls.
  • The BindDataTable() will show the user’s submitted value in the studentDataDiv.
  • On the editButton click event, I am fetching the stored values from the Session variable and showing them inside the 2 controls, so that the user can edit the stored values.

Showing description values inside CKEditor is simple done by –

descriptionTextBox.Text = "Value fetched from Database";

DEMO DOWNLOAD

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "WordPress, SEO, jQuery, HTML" and more.