如何使 TinyMCE 在 UpdatePanel 中工作?

发布于 2024-07-13 19:37:42 字数 722 浏览 4 评论 0原文

我正在尝试做许多人似乎能够做到的事情,但我无法实施任何解决方案。 TinyMCE 控件在 asp.net 表单中工作得很好,直到您用 UpdatePanel 将其括起来,然后 UpdatePanel 就会中断回发。 我已经尝试了一些修复,例如 RegisterClientScriptBlock 方法,但仍然不成功,回发后我仍然失去tinyMCE 控制。

下面是一个完整的测试项目(VS 2008),在 UpdatePanel 外部和内部都有一个控件,每个控件上都有一个用于生成回发的按钮。 另外,在该项目中,我有一个 EditorTest 控件,其中包括我尝试过的一些调用的注释代码,以防它给任何人任何想法。

代码示例

以下是 MCE 论坛上一些解决方案的一些来源:
AJAX
更新面板

I'm trying to do something that many people seem to have been able to do but which I am unable to implement any solution. The TinyMCE control works pretty well in an asp.net form until you enclose it with an UpdatePanel, which then breaks after postback. I have tried some fixes like the RegisterClientScriptBlock method, but am still unsuccessful, I still lose the tinyMCE control after postback.

Below is a full test project (VS 2008) provided with a Control outside UpdatePanel and one inside, with a button on each to generate postback. Also in the project I have a EditorTest control which include commented code of some calls I tried, in case it gives anyone any ideas.

CODE SAMPLE

Here are some sources for some solutions on the MCE forum :
AJAX
UpdatePanel

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

唠甜嗑 2024-07-20 19:37:42

要在每次 UpdatePanel 更改时执行 init,您需要使用 ScriptManager 注册脚本:

// control is your UpdatePanel
ScriptManager.RegisterStartupScript(control, control.GetType(), control.UniqueID, "your_tinymce_initfunc();", true);

注意: 您不能使用在 init 函数的 exact 模式下,您可以使用 textareasclass 选择器,否则它将无法正常工作。

您还必须使用

ScriptManager.RegisterOnSubmitStatement(this, this.GetType(), "", "tinyMCE.triggerSave();");

在 UpdatePanel 的回发上,编辑器内容不会保存在文本框中,因为默认行为仅适用于 form.submit,因此当您提交任何内容时,它将保存文本在发布之前。

在后面的代码中,要获取值,您只需要访问 TextBox.Text 属性。

注意:如果您正在使用 .NET GZipped,您可能必须放弃它,我无法让它工作,我必须完全删除它。

To execute the init everytime the UpdatePanel changes you need to register the script using ScriptManager:

// control is your UpdatePanel
ScriptManager.RegisterStartupScript(control, control.GetType(), control.UniqueID, "your_tinymce_initfunc();", true);

NOTE: You cannot use exact mode on your init function, you can use either textareas or a class selector, or else it won't work properly.

You also have to use

ScriptManager.RegisterOnSubmitStatement(this, this.GetType(), "", "tinyMCE.triggerSave();");

On a postback of a UpdatePanel the editor content isn't saved on the Textbox, because the default behavior is only for form.submit, so when you submit anything it will save the text before it posts.

On the code behind to get the value you will just need to access TextBox.Text property.

NOTE: If you are using the .NET GZipped you probably will have to drop it, I couldn't get it working, I had to remove this completely.

帅气称霸 2024-07-20 19:37:42

好吧,你的问题有两个。 Stefy 为您提供了部分答案,即您必须通过注册启动脚本来在回发时初始化 TinyMCE,如下所示:

using System.Web.UI;

namespace TinyMCEProblemDemo
{
    public partial class EditorClean : UserControl
    {
        protected void Page_Load(object sender, System.EventArgs e)
        {                
              ScriptManager.RegisterStartupScript(this.Page, 
                  this.Page.GetType(), mce.ClientID, "callInt" + mce.ClientID + "();", true);
        }
    }
}

您遇到的第二个问题是自定义控件的实现。 设计自定义控件超出了本答案的范围。 谷歌可以帮助你。

页面上有多个控件实例,这可能会导致脚本出现问题,因为它会被渲染多次。 这就是我修改标记来解决问题的方法(注意脚本函数的动态命名,自定义控件应该是自包含的,并且模式:tinyMCE.init 上的“exact”):

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="EditorClean.ascx.cs"
    Inherits="TinyMCEProblemDemo.EditorClean" %>
<script type="text/javascript" src="Editor/tiny_mce.js"></script>

<script type="text/javascript">
    function myCustomCleanup<%= mce.ClientID%>(type, value) {
        if (type == "insert_to_editor") {
            value = value.replace(/</gi, "<");
            value = value.replace(/>/gi, ">");
        }
        return value;
    }
    function myCustomSaveContent<%= mce.ClientID%>(element_id, html, body) {
        html = html.replace(/</gi, "<");
        html = html.replace(/>/gi, ">");
        return html;
    }

    function callInt<%= mce.ClientID%>() {

        tinyMCE.init({
            mode: "exact",
            elements: "<%= mce.ClientID%>",
            theme: "advanced",
            skin: "o2k7",
            plugins: "inlinepopups,paste,safari",
            theme_advanced_buttons1: "fontselect,fontsizeselect,|,forecolor,backcolor,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist,|,outdent,indent,blockquote,|,cut,copy,paste,pastetext,pasteword",
            theme_advanced_buttons2: "",
            theme_advanced_buttons3: "",
            theme_advanced_toolbar_location: "top",
            theme_advanced_toolbar_align: "left",
            cleanup_callback: "myCustomCleanup<%= mce.ClientID%>",
            save_callback: "myCustomSaveContent<%= mce.ClientID%>"
        });
    }
</script>
<textarea runat="server" id="mce" name="editor" cols="50" rows="15">Enter your text here...</textarea>

Ok, your problem is two fold. Stefy supplied you with part of the answer, which is you have to initialize TinyMCE on the postback by registering startup script like so:

using System.Web.UI;

namespace TinyMCEProblemDemo
{
    public partial class EditorClean : UserControl
    {
        protected void Page_Load(object sender, System.EventArgs e)
        {                
              ScriptManager.RegisterStartupScript(this.Page, 
                  this.Page.GetType(), mce.ClientID, "callInt" + mce.ClientID + "();", true);
        }
    }
}

The second problem you have is with your implementation of a custom control. Designing custom controls is out of scope of this answer. Google can help you there.

You have multiple instances of your control on the page which can cause you issues with script, as it get rendered multiple times. This is how I modified your markup to solve your issue(notice dynamic naming of your script functions, custom controls should be self contained and mode: "exact" on the tinyMCE.init):

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="EditorClean.ascx.cs"
    Inherits="TinyMCEProblemDemo.EditorClean" %>
<script type="text/javascript" src="Editor/tiny_mce.js"></script>

<script type="text/javascript">
    function myCustomCleanup<%= mce.ClientID%>(type, value) {
        if (type == "insert_to_editor") {
            value = value.replace(/</gi, "<");
            value = value.replace(/>/gi, ">");
        }
        return value;
    }
    function myCustomSaveContent<%= mce.ClientID%>(element_id, html, body) {
        html = html.replace(/</gi, "<");
        html = html.replace(/>/gi, ">");
        return html;
    }

    function callInt<%= mce.ClientID%>() {

        tinyMCE.init({
            mode: "exact",
            elements: "<%= mce.ClientID%>",
            theme: "advanced",
            skin: "o2k7",
            plugins: "inlinepopups,paste,safari",
            theme_advanced_buttons1: "fontselect,fontsizeselect,|,forecolor,backcolor,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist,|,outdent,indent,blockquote,|,cut,copy,paste,pastetext,pasteword",
            theme_advanced_buttons2: "",
            theme_advanced_buttons3: "",
            theme_advanced_toolbar_location: "top",
            theme_advanced_toolbar_align: "left",
            cleanup_callback: "myCustomCleanup<%= mce.ClientID%>",
            save_callback: "myCustomSaveContent<%= mce.ClientID%>"
        });
    }
</script>
<textarea runat="server" id="mce" name="editor" cols="50" rows="15">Enter your text here...</textarea>
枫以 2024-07-20 19:37:42

此解决方案不再适用于 TinyMCE 4.2.3。 现在您需要使用tinymce.remove(),而不是使用tinymce.mceRemoveControl()。 这是一个完整的工作示例:

页面

    <%@ Page Title="" Language="C#" MasterPageFile="~/MasterPages/Frame.master" AutoEventWireup="true" CodeFile="FullImplementation.aspx.cs" 
  Inherits="TinyMCE" ValidateRequest="false" %>

<asp:Content ID="Content1" ContentPlaceHolderID="cphContent" Runat="Server">

  <asp:ScriptManager runat="server"/>


  <asp:UpdatePanel runat="server" id="upUpdatPanel">
    <ContentTemplate>

      <asp:TextBox runat="server" id="tbHtmlEditor" TextMode="MultiLine">
        Default editor text
      </asp:TextBox>

      <asp:Dropdownlist runat="server" ID="ddlTest" AutoPostBack="true" OnSelectedIndexChanged="ddlTest_SelectedIndexChanged">
        <Items>
           <asp:ListItem Text="A"></asp:ListItem>
           <asp:ListItem Text="B"></asp:ListItem>
        </Items>
      </asp:Dropdownlist>

      <asp:Button runat="server" ID="butSaveEditorContent" OnClick="butSaveEditorContent_Click" Text="Save Html Content"/>      

    </ContentTemplate>
  </asp:UpdatePanel>

  <script type="text/javascript">

      $(document).ready(function () {
        /* initial load of editor */
        LoadTinyMCE();
      });

      /* wire-up an event to re-add the editor */     
      Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler_Page);

      /* fire this event to remove the existing editor and re-initialize it*/
      function EndRequestHandler_Page(sender, args) {
        //1. Remove the existing TinyMCE instance of TinyMCE
        tinymce.remove( "#<%=tbHtmlEditor.ClientID%>");
        //2. Re-init the TinyMCE editor
        LoadTinyMCE();
      }

      function BeforePostback() {
        tinymce.triggerSave();
      }

      function LoadTinyMCE() {

        /* initialize the TinyMCE editor */
        tinymce.init({
          selector: "#<%=tbHtmlEditor.ClientID%>",
          plugins: "link, autolink",
          default_link_target: "_blank",
          toolbar: "undo redo | bold italic | link unlink | cut copy paste | bullist numlist",
          menubar: false,
          statusbar: false
        });
      }

  </script>




</asp:Content>

代码隐藏:

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class TinyMCE : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    // we have to tell the editor to re-save the date on Submit 
    if (!ScriptManager.GetCurrent(Page).IsInAsyncPostBack)
    {
      ScriptManager.RegisterOnSubmitStatement(this, this.GetType(), "SaveTextBoxBeforePostBack", "SaveTextBoxBeforePostBack()");
    }

  }

  protected void butSaveEditorContent_Click(object sender, EventArgs e)
  {
    string htmlEncoded = WebUtility.HtmlEncode(tbHtmlEditor.Text);

  }

  private void SaveToDb(string htmlEncoded)
  {
    /// save to database column
  }

  protected void ddlTest_SelectedIndexChanged(object sender, EventArgs e)
  {

  }
}

This solution no longer works for TinyMCE 4.2.3. Instead of using tinymce.mceRemoveControl() you now need to use tinymce.remove(). Here is a full working example:

The Page

    <%@ Page Title="" Language="C#" MasterPageFile="~/MasterPages/Frame.master" AutoEventWireup="true" CodeFile="FullImplementation.aspx.cs" 
  Inherits="TinyMCE" ValidateRequest="false" %>

<asp:Content ID="Content1" ContentPlaceHolderID="cphContent" Runat="Server">

  <asp:ScriptManager runat="server"/>


  <asp:UpdatePanel runat="server" id="upUpdatPanel">
    <ContentTemplate>

      <asp:TextBox runat="server" id="tbHtmlEditor" TextMode="MultiLine">
        Default editor text
      </asp:TextBox>

      <asp:Dropdownlist runat="server" ID="ddlTest" AutoPostBack="true" OnSelectedIndexChanged="ddlTest_SelectedIndexChanged">
        <Items>
           <asp:ListItem Text="A"></asp:ListItem>
           <asp:ListItem Text="B"></asp:ListItem>
        </Items>
      </asp:Dropdownlist>

      <asp:Button runat="server" ID="butSaveEditorContent" OnClick="butSaveEditorContent_Click" Text="Save Html Content"/>      

    </ContentTemplate>
  </asp:UpdatePanel>

  <script type="text/javascript">

      $(document).ready(function () {
        /* initial load of editor */
        LoadTinyMCE();
      });

      /* wire-up an event to re-add the editor */     
      Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler_Page);

      /* fire this event to remove the existing editor and re-initialize it*/
      function EndRequestHandler_Page(sender, args) {
        //1. Remove the existing TinyMCE instance of TinyMCE
        tinymce.remove( "#<%=tbHtmlEditor.ClientID%>");
        //2. Re-init the TinyMCE editor
        LoadTinyMCE();
      }

      function BeforePostback() {
        tinymce.triggerSave();
      }

      function LoadTinyMCE() {

        /* initialize the TinyMCE editor */
        tinymce.init({
          selector: "#<%=tbHtmlEditor.ClientID%>",
          plugins: "link, autolink",
          default_link_target: "_blank",
          toolbar: "undo redo | bold italic | link unlink | cut copy paste | bullist numlist",
          menubar: false,
          statusbar: false
        });
      }

  </script>




</asp:Content>

The Code-Behind:

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class TinyMCE : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    // we have to tell the editor to re-save the date on Submit 
    if (!ScriptManager.GetCurrent(Page).IsInAsyncPostBack)
    {
      ScriptManager.RegisterOnSubmitStatement(this, this.GetType(), "SaveTextBoxBeforePostBack", "SaveTextBoxBeforePostBack()");
    }

  }

  protected void butSaveEditorContent_Click(object sender, EventArgs e)
  {
    string htmlEncoded = WebUtility.HtmlEncode(tbHtmlEditor.Text);

  }

  private void SaveToDb(string htmlEncoded)
  {
    /// save to database column
  }

  protected void ddlTest_SelectedIndexChanged(object sender, EventArgs e)
  {

  }
}
倦话 2024-07-20 19:37:42

使tinyMCE 在更新面板中工作的正确方法:

1) 为“提交”按钮的OnClientClick 创建一个处理程序。

2) 运行tinyMCE.execCommand("mceRemoveControl", false, '<%= txtMCE.ClientID %>'); 在处理程序中,以便在回发之前删除tinyMCE实例。

3) 在异步回发中,使用 ScriptManager.RegisterStartupScript 运行tinyMCE.execCommand("mceAddControl", true, '<%= txtMCE.ClientID %>');

基本上,您需要做的就是在异步回发之前使用 mceRemoveControl 命令,并注册一个启动脚本以在异步回发之后运行 mceAddControl 命令。 不太难。

The correct way to make tinyMCE work in an updatepanel:

1) Create a handler for the OnClientClick of your "submit" button.

2) Run tinyMCE.execCommand("mceRemoveControl", false, '<%= txtMCE.ClientID %>'); in the handler, so as to remove the tinyMCE instance before the postback.

3) In your async postback, use the ScriptManager.RegisterStartupScript to run tinyMCE.execCommand("mceAddControl", true, '<%= txtMCE.ClientID %>');

Basically, all you need to do is use the mceRemoveControl command before the async postback and register a startup script to run the mceAddControl command after the async postback. Not too tough.

无声静候 2024-07-20 19:37:42

我执行了以下操作:

首先,我将此 Javascript 添加到我的页面中:

<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);

function endRequestHandler(sender,args)
{
    tinyMCE.idCounter=0;
    tinyMCE.execCommand('mceAddControl',false,'htmlContent');
}

function UpdateTextArea()
{ 
    tinyMCE.triggerSave(false,true);
}
</script>

因为我正在创建 ASP.NET 并在页面中使用 ASP.NET 按钮,所以我必须将以下内容添加到页面加载中:

protected void Page_Load(object sender, EventArgs e)
{
    Button1.Attributes.Add("onclick", "UpdateTextArea()");
}

I did the following:

First I added the this Javascript to my page:

<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);

function endRequestHandler(sender,args)
{
    tinyMCE.idCounter=0;
    tinyMCE.execCommand('mceAddControl',false,'htmlContent');
}

function UpdateTextArea()
{ 
    tinyMCE.triggerSave(false,true);
}
</script>

Because I'm creating an ASP.NET and using and ASP.NET Button in my page, I had to add the following to the Page Load:

protected void Page_Load(object sender, EventArgs e)
{
    Button1.Attributes.Add("onclick", "UpdateTextArea()");
}
倾城花音 2024-07-20 19:37:42

这是一个老问题,但是经过几个小时的搜索和混乱寻找答案后,我觉得有义务发布我想出的解决方案。

看来,至少在我使用的实现中(UpdatePanel 内的多个编辑器),当 UpdatePanel 提交时,必须通知 tinyMCE 控件即将消失,否则它将拒绝再次加载。

因此,除了 Init TinyMCE 的代码(仅需要在整个页面加载时运行)之外,您还需要为每个 MCE 文本框执行此操作:

ScriptManager.RegisterStartupScript(this, this.GetType(), elm1.UniqueID+"Add",
    "tinyMCE.execCommand('mceAddControl', true,'" + elm1.ClientID + "');", true);
ScriptManager.RegisterOnSubmitStatement(this, this.GetType(), elm1.UniqueID + "Remove",
    "tinyMCE.execCommand('mceRemoveControl', true,'" + elm1.ClientID + "');");

elm1 是 tinyMCE 元素的名称。 我的文本区域驻留在用户控件中,但您可以将其应用到您想要绑定/取消绑定文本区域的任何项目。

This is an old question, but after hours searching and messing around looking for the answer, I feel obligated to post the solution I came up with.

It appears that, at least in the implementation I'm using (multiple editors inside an UpdatePanel) that tinyMCE must be informed the control is going away when the UpdatePanel submits, or else it will refuse to load it again.

So, in addition to the code to Init TinyMCE (which only needs to run when the whole page loads) you need to do this for each of your MCE textboxes:

ScriptManager.RegisterStartupScript(this, this.GetType(), elm1.UniqueID+"Add",
    "tinyMCE.execCommand('mceAddControl', true,'" + elm1.ClientID + "');", true);
ScriptManager.RegisterOnSubmitStatement(this, this.GetType(), elm1.UniqueID + "Remove",
    "tinyMCE.execCommand('mceRemoveControl', true,'" + elm1.ClientID + "');");

elm1 is whatever the tinyMCE element is. Mine is a textarea residing in a UserControl, but you can apply it to any item you want to bind/unbind your textarea.

旧时光的容颜 2024-07-20 19:37:42

为使用 .NET Framework 4 的用户更新此问题的答案,我通过插入以下内容成功将 TinyMCE 附加到更新面板内的文本框:

在 内的标记中 区域:

<script src="scripts/tinymce/tinymce.min.js" type="text/javascript"></script>
<script type="text/javascript">

    tinyMCE.init({
        selector: ".tinymcetextarea",
        mode: "textareas",

        plugins: [
             "advlist autolink link image lists charmap print preview hr anchor pagebreak spellchecker",
             "searchreplace visualblocks visualchars code fullscreen autoresize insertdatetime media nonbreaking",
             "save table contextmenu directionality emoticons template paste textcolor",
             "autosave codesample colorpicker image imagetools importcss layer"
        ],

        toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | print preview media | forecolor backcolor emoticons",
        style_formats: [
             { title: 'Bold text', inline: 'b' },
             { title: 'Red text', inline: 'span', styles: { color: '#ff0000' } },
             { title: 'Red header', block: 'h1', styles: { color: '#ff0000' } },
             { title: 'Example 1', inline: 'span', classes: 'example1' },
             { title: 'Example 2', inline: 'span', classes: 'example2' },
             { title: 'Table styles' },
             { title: 'Table row 1', selector: 'tr', classes: 'tablerow1' }
        ]
    });

</script>

在 内的标记中 区域:

<asp:TextBox ID="tbContentHtml" CssClass="tinymcetextarea" Wrap="true" runat="server" Width="90%" TextMode="MultiLine" />

最后在 Page_Load 事件的代码隐藏中:

ScriptManager.RegisterStartupScript(this, this.GetType(), tbContentHtml.UniqueID + "Add", "tinyMCE.execCommand('mceAddEditor', true,'" + tbContentHtml.ClientID + "');", true);
ScriptManager.RegisterOnSubmitStatement(this, this.GetType(), tbContentHtml.UniqueID + "Remove", "tinyMCE.execCommand('mceRemoveEditor', true,'" + tbContentHtml.ClientID + "');");

Updating the answer to this question for those using .NET framework 4, I was successful in attaching TinyMCE to a TextBox inside an update panel by inserting the following:

In markup within the <head></head> region:

<script src="scripts/tinymce/tinymce.min.js" type="text/javascript"></script>
<script type="text/javascript">

    tinyMCE.init({
        selector: ".tinymcetextarea",
        mode: "textareas",

        plugins: [
             "advlist autolink link image lists charmap print preview hr anchor pagebreak spellchecker",
             "searchreplace visualblocks visualchars code fullscreen autoresize insertdatetime media nonbreaking",
             "save table contextmenu directionality emoticons template paste textcolor",
             "autosave codesample colorpicker image imagetools importcss layer"
        ],

        toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | print preview media | forecolor backcolor emoticons",
        style_formats: [
             { title: 'Bold text', inline: 'b' },
             { title: 'Red text', inline: 'span', styles: { color: '#ff0000' } },
             { title: 'Red header', block: 'h1', styles: { color: '#ff0000' } },
             { title: 'Example 1', inline: 'span', classes: 'example1' },
             { title: 'Example 2', inline: 'span', classes: 'example2' },
             { title: 'Table styles' },
             { title: 'Table row 1', selector: 'tr', classes: 'tablerow1' }
        ]
    });

</script>

In the markup within the <body></body> region:

<asp:TextBox ID="tbContentHtml" CssClass="tinymcetextarea" Wrap="true" runat="server" Width="90%" TextMode="MultiLine" />

And finally in codebehind in the Page_Load event:

ScriptManager.RegisterStartupScript(this, this.GetType(), tbContentHtml.UniqueID + "Add", "tinyMCE.execCommand('mceAddEditor', true,'" + tbContentHtml.ClientID + "');", true);
ScriptManager.RegisterOnSubmitStatement(this, this.GetType(), tbContentHtml.UniqueID + "Remove", "tinyMCE.execCommand('mceRemoveEditor', true,'" + tbContentHtml.ClientID + "');");
陈甜 2024-07-20 19:37:42

每当更新面板刷新时,您都必须调用 TinyMCE 的初始化方法。

为此,您必须从 RegisterStartupScript 方法调用此方法 (tinyMCE.init),或者在页面的 head 部分创建页面加载 javascript 函数,如下所示:

function pageLoad() {
   tinyMCE.init();
}

每次刷新更新面板时都会执行此函数。

You have to call the initializing method of the TinyMCE whenever the update panel is refreshed.

For this, you have either to call this method (tinyMCE.init) from a RegisterStartupScript method, or to create a page load javascript function in the head section of the page like this:

function pageLoad() {
   tinyMCE.init();
}

This function will be executed each time the update panel is refreshed.

你是我的挚爱i 2024-07-20 19:37:42

我解决了这个问题
在 ajax 调用的响应生成

function edittemp(name) {

xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Your browser does not support XMLHTTP!");
return;
}


var url="edit_temp.php";
url=url+"?id="+name;





xmlhttp.onreadystatechange=stateChanged3;
xmlhttp.open("GET",url,true);
xmlhttp.send(null); 


}
function stateChanged3()
{
if (xmlhttp.readyState==4)
{
spl_txt=xmlhttp.responseText.split("~~~");


document.getElementById("edit_message").innerHTML=spl_txt[0];   
tinyMCE.init({
theme : "advanced",
mode: "exact",
elements : "elm1",
theme_advanced_toolbar_location : "top",
theme_advanced_buttons1 : "bold,italic,underline,strikethrough,separator,"
+ "justifyleft,justifycenter,justifyright,justifyfull,formatselect,"
+ "bullist,numlist,outdent,indent",
theme_advanced_buttons2 : "link,unlink,anchor,image,separator,"
+"undo,redo,cleanup,code,separator,sub,sup,charmap",
theme_advanced_buttons3 : "",
height:"350px",
width:"600px"
});
}
}

和 ajax 调用生成的页面

<?php
$name=$_GET['id'];
include 'connection.php';
$result=mysql_query("SELECT * FROM `templete` WHERE temp_name='$name' and status=1");

$row = mysql_fetch_array($result);
$Content=$row['body'];
?>
<html>
<head>
<title>editing using tiny_mce</title>
<script language="..." src="tinymce/jscripts/tiny_mce  /tiny_mce.js"></script>
</head>
<body>
<h2>change the template here</h2>
<form method="post" action="save_temp.php?name=<?php echo $name;?>">
<textarea id="elm1" name="elm1" rows="15" cols="80"><?php echo $Content;?></textarea>
<br />
<input type="submit" name="save" value="Submit" />
<input type="reset" name="reset" value="Reset" />
</form>
</body>
</html>

之后调用tiny mce在这种情况下可能会有所帮助。

i solved this problem as
call tiny mce after the response generation of the ajax call

function edittemp(name) {

xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Your browser does not support XMLHTTP!");
return;
}


var url="edit_temp.php";
url=url+"?id="+name;





xmlhttp.onreadystatechange=stateChanged3;
xmlhttp.open("GET",url,true);
xmlhttp.send(null); 


}
function stateChanged3()
{
if (xmlhttp.readyState==4)
{
spl_txt=xmlhttp.responseText.split("~~~");


document.getElementById("edit_message").innerHTML=spl_txt[0];   
tinyMCE.init({
theme : "advanced",
mode: "exact",
elements : "elm1",
theme_advanced_toolbar_location : "top",
theme_advanced_buttons1 : "bold,italic,underline,strikethrough,separator,"
+ "justifyleft,justifycenter,justifyright,justifyfull,formatselect,"
+ "bullist,numlist,outdent,indent",
theme_advanced_buttons2 : "link,unlink,anchor,image,separator,"
+"undo,redo,cleanup,code,separator,sub,sup,charmap",
theme_advanced_buttons3 : "",
height:"350px",
width:"600px"
});
}
}

and the page caaled by ajax call is

<?php
$name=$_GET['id'];
include 'connection.php';
$result=mysql_query("SELECT * FROM `templete` WHERE temp_name='$name' and status=1");

$row = mysql_fetch_array($result);
$Content=$row['body'];
?>
<html>
<head>
<title>editing using tiny_mce</title>
<script language="..." src="tinymce/jscripts/tiny_mce  /tiny_mce.js"></script>
</head>
<body>
<h2>change the template here</h2>
<form method="post" action="save_temp.php?name=<?php echo $name;?>">
<textarea id="elm1" name="elm1" rows="15" cols="80"><?php echo $Content;?></textarea>
<br />
<input type="submit" name="save" value="Submit" />
<input type="reset" name="reset" value="Reset" />
</form>
</body>
</html>

may be helpful in such situation.

无远思近则忧 2024-07-20 19:37:42

我这样

<script language="javascript" type="text/javascript">
    function pageLoad(sender, args) { 
        aplicartinyMCE();     
    }
    function aplicartinyMCE() {
       tinyMCE.init({
           mode: "specific_textareas",
           editor_selector: "mceEditor",
           .....
       });
    }
</script>

在每次异步回发后初始化编辑器,即使然后

在 page_load 事件中

ScriptManager.RegisterOnSubmitStatement(this, this.GetType(), "salvarEditorMCE", "tinyMCE.triggerSave();");

I di this

<script language="javascript" type="text/javascript">
    function pageLoad(sender, args) { 
        aplicartinyMCE();     
    }
    function aplicartinyMCE() {
       tinyMCE.init({
           mode: "specific_textareas",
           editor_selector: "mceEditor",
           .....
       });
    }
</script>

That initialize the editor after each asynchronous postback even if

Then in page_load event

ScriptManager.RegisterOnSubmitStatement(this, this.GetType(), "salvarEditorMCE", "tinyMCE.triggerSave();");
昇り龍 2024-07-20 19:37:42

TinyMCE(以及其他所见即所得编辑器、FCKEditor 等)存在回发验证问题。 默认情况下,回发时的任何 ASP.Net 页面都会检查其内容,并且任何未编码的 HTML 都会引发回发验证错误。

现在,包括这些论坛上的许多人建议禁用回发验证 validaterequest="false" ,但这使您容易受到脚本攻击,最好的办法是将函数绑定到在异步回发之前触发的异步回发事件。 此 JavaScript 函数需要对要回传到服务器的 TinyMCE 数据进行 HTML 编码,然后这将通过回发验证,然后就可以了。

我相信 TinyMCE 和其他编辑器在回发上正确地执行此操作,但不是异步回发,因此出现了问题,事实上,如果您查看 TinyMCE 的源代码,您可能会发现他们的函数可以执行此操作并只需添加事件绑定。

希望这可以帮助

TinyMCE (as well as other WYSIWYG editors, FCKEditor etc) suffers from postback validation issues. By default any ASP.Net page on postback has its contents checked, and any unencoded HTML throws the postback validation error.

Now many people, including on those forums suggest disabling the postback validation, validaterequest="false" , but this makes you susceptible to scripting attacks, the best thing to do is bind a function to the async postback event that fires off just before async postback. This JavaScript function needs to HTML encode the TinyMCE data being posted back to the server, this will then pass the postback validation and you'll be OK.

I believe TinyMCE and other editors correctly do this on postbacks but not async postbacks hence the issue, in fact if you look at TinyMCE's source you can probably find their function that does this and simply add the event binding.

Hope this helps

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文