Convert string to WebControls - asp.net

 ̄綄美尐妖づ 提交于 2019-12-04 17:37:59

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!