【问题标题】:Get the updated html content of asp:Literal or div in server side when modified by jqueryjquery修改时获取服务器端asp:Literal或div更新后的html内容
【发布时间】:2017-08-23 14:18:13
【问题描述】:

我目前有一系列传递给文字 asp 控件的 html 代码。

Labelhighlight.Text = <strong>foo sample</strong>;

在我的视图中,这里是我使用的控件

<div id="highlightedtext" class="well" runat="server"> 
  <asp:Literal ID="Labelhighlight" runat="server" Mode="PassThrough">
  </asp:Literal>
  </asp:Label>
</div>  

然后在我的客户端,我使用 jquery 包装了一个字符串,结果为

<div id="highlightedtext" class="well">
  <string>foo <span id='test'>sample</span> </strong>
</div>

然后在我的服务器端,我应该在按钮单击时获得更新的 html 内容 这是后面的代码:

protected void btnSave_Click(object sender, EventArgs e)
{
  var test = RenderControl(Labelhighlight);
}

public string RenderControl(System.Web.UI.Control ctrl)
{
  StringBuilder sb = new StringBuilder();
  StringWriter tw = new StringWriter(sb);
  HtmlTextWriter hw = new HtmlTextWriter(tw);

  ctrl.RenderControl(hw);
  return sb.ToString();
}

我只得到之前的 html 字符串 &lt;strong&gt;foo sample&lt;/strong&gt;。我也尝试获取 div 的 html 内容,但出现以下错误:Cannot get inner content of because the contents is not literal.

【问题讨论】:

  • 欢迎来到 Stack Overflow。看起来您的 HTML 中可能存在一些语法错误。请检查您的 ASP 代码和 HTML 代码。还请检查您的浏览器控制台是否有任何 JavaScript 错误。
  • 感谢您的回复,我使用 jquery 在文本周围插入 span 标签的代码正在浏览器上运行。它只是不更新​​文字控件周围的内容。也许我需要一个将代码保存在文字上的 jquery 我不确定是否可能。
  • 当您在 jQuery 中工作时,这只是客户端的更改,除非经过编程,否则它们不会发布回服务器端。那么,服务器如何知道文字内容发生了变化呢?它已经解析并发送到服务器。

标签: jquery html asp.net asp.net-web-api


【解决方案1】:

我找到了一种不使用 runat="server" 将内容保存到隐藏 div 的方法,然后使用请求表单在我的服务器端获取内容,代码如下:

<input type="hidden" id="div_content" name="div_content" />

然后在我的 jquery 上

   function SaveToHidden() {

                     var content = document.getElementById("highlightedtext").innerHTML;

                     document.getElementById("div_content").value = content;
                 };
    </script>

【讨论】:

    猜你喜欢
    • 2012-02-04
    • 1970-01-01
    • 2013-07-24
    • 1970-01-01
    • 2015-08-20
    • 1970-01-01
    • 1970-01-01
    • 2018-07-06
    • 1970-01-01
    相关资源
    最近更新 更多