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
}
}
hope this helps,
string myInnerHtml = @"<table>
<colgroup>col width='100'/></colgroup>
<tbody>
<tr>
<td>hello 1</td><td>hello 2</td>
</tr>
<tr>
<td>hello 3</td><td>hello 4</td>
</tr>
</tbody>
</table>";
DataSet ds = new DataSet();
ds.ReadXml(new XmlTextReader(new StringReader(myInnerHtml)));
var tr = ds.Tables["tr"];
var td = ds.Tables["td"];
foreach (DataRow trRow in tr.Rows)
foreach(DataRow tdRow in td.AsEnumerable().Where(x => (int)x["tr_Id"] == (int)trRow["tr_Id"]))
Console.WriteLine( tdRow["tr_Id"] + " | " + tdRow["td_Text"]);
output
=========================
//0 | hello 1
//0 | hello 2
//1 | hello 3
//1 | hello 4
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;
}
}
}
}
}
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.