字符串转换为器WebControls - asp.net [英] Convert string to WebControls - asp.net
问题描述
如果你看到下面的code
If you see the following code
Table tblTest = (Table)tblControl;
StringBuilder text = new StringBuilder();
StringWriter writer = new StringWriter(text);
HtmlTextWriter htmlWriter = new HtmlTextWriter(writer);
tblTest.RenderControl(htmlWriter);
htmlCode = text.ToString();
在这里我表对象转换为字符串。
here i am converting a table object to string.
我会得到的输出为<表>< TR>< TD>项目< / TD>< / TR>< /表>
现在我想回滚它。我有一个字符串,我需要将其转换成WebControls.Table对象。请人提出了一些办法。
Now i want to Rollback it. I am having a string and i need to convert that into WebControls.Table object. Please someone suggest some way.
推荐答案
在地图上添加一个HTMLLoader对象呈现与在控制了名的。然后,你可以把发送给你的XML字符串,并使用 XDocument.Parse
加载它。从那里,你可以递归构建控制结构。
Create a map of the name an HtmlControl is rendered with to the control. Then you can take the xml string sent to you and load it using XDocument.Parse
. From there you can recursively build the control structure.
Dictionary<string, HtmlContainerControl> controlConstructor = new Dictionary<string, HtmlContainerControl>
{
{"table", new HtmlTable()},
{"tr", new HtmlTableRow()},
{"td", new HtmlTableCell()}
};
string xml = "<table><tr><td>item</td></tr></table>";
var htmlDoc = XElement.Parse(xml);
Func<XElement, HtmlControl> constructHtmlStructure = null;
constructHtmlStructure = e =>
{
var control = controlConstructor[e.Name.ToString()];
if (e.HasElements)
control.Controls.Add(constructHtmlStructure(e.Elements().Single()));
else
control.InnerText = e.Value;
return control;
};
var structure = constructHtmlStructure(htmlDoc);
是一个非常简单的开始。你需要的东西复杂得多得到所有的控件。需要注意的是他们有,您可以使用捕捉到所有控件构建你的字典标记名属性。
Is a very simple start. You'll need something much more complicated to get all controls. Note that they have a TagName property which you can use to capture all controls in building your dictionary.
这篇关于字符串转换为器WebControls - asp.net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!