无法在 asp.net c# 中保存可编辑 div 的 innerText/innerHTML

Can't save innerText / innerHTML of an editable div in asp.net c#

我尝试保存可编辑div的更改文本。我在页面加载时将一些文本放入 div 并在浏览器中更改它,但我无法保存更改,因为 innerHTML 内容没有更改。

这是我的 aspx 文件:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Title</title>
</head>
<body>
    <form id="form1" runat="server">
      <div contenteditable="true" runat="server" id="txtText" ></div>
      <asp:Button ID="btnSave" runat="server" Text="Speichern" OnClick="btnSave_Click" />
    </form>
</body>
</html>

这是文件背后的代码:

public partial class editWordModule : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            txtText.InnerHTML = "This is the unmodified text";
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            string test = txtText.InnerHtml;
            //still shows "This is the unmodified text" while it was changed before in the div

        }
    }
}

那么如何保存 div 的编辑后的 ​​innerHTML?

用JavaScript做个小把戏。 单击按钮时,获取DIV的innerHTML并放入asp:HiddenField

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
       <title>Title</title>
    </head>
    <body>
        <script type="text/javascript">
        function ChangeDiv() {
            var div = document.getElementById("txtText");
            var hdn = document.getElementById("hdnText");
            hdn.value = div.innerHTML;
        }
        </script>

        <form id="form1" runat="server">
            <div contenteditable="true" id="txtText"></div>
            <asp:HiddenField ID="hdnText" runat="server" ClientIDMode="Static" />
            <asp:Button ID="btnSave" runat="server" Text="Speichern" OnClick="btnSave_Click" OnClientClick="ChangeDiv()" />
        </form>
    </body>
</html>

并在您的代码后面读取隐藏字段。

string hdn = hdnText.Value