asp.net - 如何获取动态更改的div块的内容

时间:2016-09-26 17:26:37

标签: javascript c# asp.net

我是asp.net的新手,我正在尝试获取div块的内容,其内容在运行时更改。当用户点击Button1(asp:按钮)时,我希望它能够检索frm_div的整个内容(不仅仅是默认内容),并将其显示在frm_div2中。任何建议都表示赞赏。

protected void Button1_Click(object sender, EventArgs e)
       {
          //WOuld like to get the content of frm_div not just default content and put it in frm_div2
          frm_div2.InnerHtml = frm_div.InnerHtml;
    string buf = TextBox1.Text;
    changed_text.InnerHtml = buf.ToUpper(); 
}

    <form id="form1" runat="server">
      <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true"></asp:ScriptManager>
     <div>

        <asp:TextBox ID="TextBox1" runat="server" style="width:224px">
        </asp:TextBox>
        <br />
        <br />  
        <asp:Button ID="Button1" runat="server" Text="Enter..." style="width:85px" onclick="Button1_Click" />
        <hr />

        <h3> Results: </h3>
        <span runat="server" id="changed_text" />

     </div>

       <button id="ClickFunc" type="button" value="Hello" onclick="func();">Click</button>

      <div id="frm_div" runat="server">
            -----
       </div>
      <div id="frm_div2" runat="server">
      </div>

  </form>

   <script type="text/javascript">
        function func() {
       document.getElementById('frm_div').innerHTML = '<p>' + document.getElementById('frm_div').innerHTML + '  <b>client side added</b> </p>';
      }
     </script>  

2 个答案:

答案 0 :(得分:0)

添加隐藏输入,并在func()中使用内容填充隐藏输入的值。

[... snip ...]
<asp:Hidden id="myhidden" runat="server" />

[... snip ...]
function func() {
    document.getElementById('frm_div').innerHTML = 
        '<p>' + 
        document.getElementById('frm_div').innerHTML + 
        '  <b>client side added</b> </p>';

    document.getElementById('myhidden').value = 
        document.getElementById('frm_div').innerHTML;
}

然后在按钮单击服务器处理程序中,您可以访问值:

protected void Button1_Click(object sender, EventArgs e)
{
    string v = myhidden.value;
}

为了避免安全错误,您需要HtmlEncode值:

function HtmlEncode(str) {
    return str
        .replace(/&/g, '&amp;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;');
}

function func() {
    document.getElementById('frm_div').innerHTML = 
        '<p>' + 
        document.getElementById('frm_div').innerHTML + 
        '  <b>client side added</b> </p>';

    document.getElementById('myhidden').value = 
        HtmlEncode(document.getElementById('frm_div').innerHTML);
}

在服务器端,您可能需要HtmlDecode()值。

答案 1 :(得分:0)

我终于想出了这个,但花了一些时间才开始工作。

当您获得div的 innerHTML 时,它仅包含您的html标记仅限于值属性而不包含值属性这是用户在加载页面后输入的文本。首先要做的是使用客户端脚本来设置value attribute = value属性。然后,您可以使用WebMethod获取innerHTML并将其传递给您的代码隐藏。

这是一个代码snippit,它设置输入的属性值,抓取innerHTML并将其传递给WebMethod:

function updateInputsValueAttribute() {
  var div = document.getElementById('DivContainer').getElementsByTagName('input');
  for (var i = 0; i < div.length; i++) {
      // set attribute value to property value
      div[i].setAttribute("value", div[i].value);
  }

  var dataValue = HtmlEncode(document.getElementById('DivContainer').innerHTML);
  $.ajax({
      type: "POST",
      url: "CurrentPage.aspx/MethodToPassResult",
      data: "{sendData: '" + dataValue + "'}",
      contentType: "application/json; charset=utf-8",
      //dataType: 'json',
      error: function (XMLHttpRequest, textStatus, errorThrown) {
          //alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
      },
      success: function (result) {
          if (result.d == "failed") {

          }
          else {
              //result.d contains the resulting string from the code behind C# method
          }
      }
  });
}
function HtmlEncode(str) {
    return str
        .replace(/&/g, '&amp;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;');
}
After you update the text in the input and press the button <br/>the attribute value will be updated and the Ajax method will be called <br/>passing the contents of the div to the WebMethod in the C# codebehind class. Please note the Html Encoding and Decoding using the custom function from the other answer provided and HttpUtility is used to prevent security errors.
<hr/>

<div id="DivContainer" runat="server">
<input type="text" value="Value Attribute"/>
</div>
<input type="button" onclick="updateInputsValueAttribute();" value="Do Something" />

以下是CurrentPage.aspx类中WebMethod的标记。我使用HtmlAgilityPack来解析innerHTML结果:

using HtmlAgilityPack;
using System.Web.Services;

public partial class CurrentPage : System.Web.UI.Page
{
    [WebMethod(EnableSession = true)]
    public static string MethodToPassResult(string sendData)
    {
        String currentHtml = HttpUtility.HtmlDecode(sendData);
        byte[] byteArray = Encoding.UTF8.GetBytes(currentHtml);
        MemoryStream stream = new MemoryStream(byteArray);
        HtmlDocument html = new HtmlDocument();
        html.Load(stream);
        HtmlDocument HTMLDocument = html;
        HtmlDocument HTMLDocumentDiv = new HtmlDocument();
        //Do something here such as iterate through all divs
        var itemList = HTMLDocument.DocumentNode.SelectNodes("//div")
              .Select(p => p)
              .ToList();
        return "result string from code behind";
    }
}

从那里你应该能够把它连接起来做你需要的。我希望这有帮助!