简体   繁体   中英

asp.net - How to get content of dynamically changed div block

I am fairly new to asp.net and I am trying to get the content of a div block, that its content is is changed at run time. When user click on Button1 (asp:button) I would like it to retrieve the whole content (not just default content) of frm_div and display it in frm_div2. Any suggestion is appreciated.

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>  

Add a hidden input and in func() populate the hidden input's value with the content.

[... 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;
}

Then in your button click server handler you can access the value:

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

To avoid security errors you'll want to HtmlEncode the value:

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);
}

On the server side you may want to HtmlDecode() the value.

I finally figured this one out but took some time to get working.

When you are getting the innerHTML of the div it is only including your html markup limited to the value attribute and not the value property which is the text the user has entered after the page loaded. What you must do first is use client side scripting to set the value attribute = value property. You can then grab the innerHTML and pass that to your codebehind using a WebMethod.

Here is a code snippit that sets the attribute values for inputs, grabs the innerHTML and passes it to a 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" /> 

Here is the markup for the WebMethod in your CurrentPage.aspx class. I use HtmlAgilityPack to parse through the innerHTML result:

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";
    }
}

From there you should be able to wire it up to do what you need. I hope this helps!

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