简体   繁体   中英

How to keep the state of HTML div after postback

I use CKEditor in my webform application like this:

  <div class="editor" runat="server" EnableViewState="true">
       <div cols="10" id="editor1" name="editor1" data-sample-short contenteditable="true" runat="server" EnableViewState="true">
          TEST
       </div>
   </div>

I want to get editor1.InnerText after postback, and I can't because it's stateless HTML div, and at the same time I can't use server control equivalent because I already handled the required events on this control. How to keep the data after postback?

Use a hidden Text Field as follows:

<asp:TextBox ID="tbTransfer" runat="server" TextMode="Multiline"></asp:TextBox>

In Javascript:

//Set Transfer Textbox display to none
document.getElementById('MainContent_tbTransfer').style.display = "none";

//Set Initial Source Code of CKEditor to Transfer TextBox's value
CKEDITOR.instances.editor1.setData(document.getElementById('MainContent_tbTransfer').value);

//Use this function for when you want to do the PostBack
function PostBack() {
    var temp = CKEDITOR.instances.editor1.getData();

    document.getElementById('MainContent_tbTransfer').value = temp.replace(/</g, "d123").replace(/>/g, "d321").replace(/&/g,"d111");
}

In Code Behind:

//Getting the HTML source code of CKEditor from the Transfer Textbox and Decrypting it
string htmlToSave = tbTransfer.Text.Replace("d123", "<").Replace("d321", ">").Replace("d111", "&");

//Setting back the Transfer Textbox's text to the decrypted HTML source code
//for when the page reloads at the end of the function,
//CKEditor sets its data = Transfer Textbox's Text
tbTransfer.Text = htmlToSave;

Encryption and Decryption of the HTML Code are necessary since Web Browsers will recognize the characters '<','>','&' as HTML tags and will not let you post back with plain HTML Text inside the Text box.

And do not forget to change 'MainContent_tbTransfer' if your text box has a different id in the browser

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM