我在客户端生成了一个 HTML 行 ( <tr>
),我想将包含行单元格信息的字符串转换为 HtmlTableRow
控制。这就是我到目前为止使用 Convert string to WebControls - asp.net 上的示例所做的。 .谢谢
string row = "<tr><td>item</td><td><input name=\"radio0\" type=\"radio\"/></td></tr>";
Dictionary<string, HtmlContainerControl> controlConstructor = new Dictionary<string, HtmlContainerControl>
{
{"tr", new HtmlTableRow()},
{"td", new HtmlTableCell()}
};
var htmlDoc = XElement.Parse(row);
Func<XElement, HtmlControl> constructHtmlStructure = null;
constructHtmlStructure = (o =>
{
var control = controlConstructor[o.Name.ToString()];
if (o.HasElements)
{
control.Controls.Add(constructHtmlStructure(o.Elements().Single())); //Exception: Sequence contains more than one element (When is a input item)
}
else
{
control.InnerText = o.Value;
}
return control;
});
HtmlTableRow structure = (HtmlTableRow)constructHtmlStructure(htmlDoc);
最佳答案
为什么不使用更简单的方法将字符串解析为 HtmlTableRow。
你的Dictionary<string, HtmlContainerControl> controlConstructor
只考虑 tr
和 td
,嵌套在其中的输入控件呢?
因此,即使您通过“sequence contains more than one element
”逃脱,使用 foreach 循环,您也会收到错误 "key doesn't exist
。 ".
即使您设法克服了这个问题(通过在字典中添加输入键),您也无法将其解析为 HtmlContainerControl
。 .
即使您这样做了,也可以更新您的 Dictionary<string, HtmlContainerControl>
至 Dictionary<string, HtmlControl>
,你将不得不想办法处理那个输入控件,因为你不能这样做 control.InnerText = o.value;
因此有一个更简单的方法:
string row = "<tr><td>item</td><td><input name=\"radio0\" type=\"radio\"/></td></tr>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(row);
HtmlTableRow tblRow = new HtmlTableRow();
foreach (XmlNode node in doc.SelectSingleNode("tr").ChildNodes)
{
HtmlTableCell cell = new HtmlTableCell();
cell.InnerText = node.InnerXml;
foreach (XmlNode childNode in node.ChildNodes)
{
if (childNode.Name == "input")
{
if (childNode.Attributes["type"] != null)
{
switch (childNode.Attributes["type"].Value.ToString())
{
case "radio":
HtmlInputRadioButton rad = new HtmlInputRadioButton();
rad.Name = childNode.Attributes["name"].ToString();
cell.Controls.Add(rad);
break;
///other types of input controls
default:
break;
}
}
else
{
HtmlInputButton button = new HtmlInputButton("button");
cell.Controls.Add(button);
}
}
}
tblRow.Cells.Add(cell);
}
正如你所看到的,这是一个非常粗略和严格的逻辑:你能做的最好的就是想出一个递归函数,来构造你的 HtmlTableRow
关于c# - 将字符串转换为 HtmlTableRow 控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15179069/