使用InnerHtml字符串从C#服务器端构建HTML表

时间:2014-11-12 20:00:30

标签: c# asp.net htmlcontrols

我试图在我的c#服务器端循环我的客户端Html表内容。将Html表设置为runat="server"不是一个选项,因为它与正在使用的javascript冲突。

我使用ajax将我的客户端html表的InnerHtml传递给我的服务器端方法。我以为我能够在c#中简单地创建一个HtmlTable变量,并在我很快意识到这是不可能的时候设置InnerHtml属性,因为我收到错误{"'HtmlTable' does not support the InnerHtml property."}

为简单起见,假设我从客户端传递到服务器的InnerHtml字符串是:

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

我跟踪了另一个堆栈溢出问题的帖子,但无法让它正常工作。

有人可以指出我的错误吗?

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

    }
}

2 个答案:

答案 0 :(得分:0)

希望这有帮助,

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

答案 1 :(得分:0)

使用HTMLAgilityPack结束。我发现它对于各种情况更具可读性和可管理性。

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