Search code examples
c#asp.nethtmlcontrols

Build HTMLTable from C# Serverside with InnerHtml string


I am trying to loop through my client side Html table contents on my c# server side. Setting the Html table to runat="server" is not an option because it conflicts with the javascript in use.

I use ajax to pass my clientside html table's InnerHtml to my server side method. I thought I would be able to simple create an HtmlTable variable in c# and set the InnerHtml property when I quickly realized this is not possible because I got the error {"'HtmlTable' does not support the InnerHtml property."}

For simplicity , lets say my InnerHtml string passed from client to server is:

string myInnerHtml = "<colgroup>col width="100"/></colgroup><tbody><tr><td>hello</td></tr></tbody>"

I followed a post from another stack overflow question but can not quite get it working.

Can someone point out my errors?

string myInnerHtml = "<colgroup>col width="100"/></colgroup><tbody><tr><td>hello</td></tr></tbody>"

HtmlTable table = new HtmlTable();
System.Text.StringBuilder sb = new System.Text.StringBuilder(myInnerHtml);
System.IO.StringWriter tw = new System.IO.StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(tw);
table.RenderControl(hw);

for (int i = 0; i < table.Rows.Count; i++)
{
    for (int c = 0; c < table.Rows[i].Cells.Count; i++)
    {
        // get cell contents

    }
}

Solution

  • Ended up using the HTMLAgilityPack. I found it a lot more readable and manageable for diverse situations.

        HtmlDocument doc = new HtmlDocument();
        doc.LoadHtml("<html><body><table>" + innerHtml + "</table></html></body>");
    
        foreach (HtmlNode table in doc.DocumentNode.SelectNodes("//table"))
        {
            foreach (HtmlNode row in table.SelectNodes("//tr"))
            {
                foreach (HtmlNode cell in row.SelectNodes("td"))
                {
                    var divExists = cell.SelectNodes("div");
                    if (divExists != null)
                    {
                        foreach (HtmlNode div in cell.SelectNodes("div"))
                        {
                            string test = div.InnerText + div.Attributes["data-id"].Value;
                        }
                    }
                }
            }
       }