Convert string to WebControls - asp.net

别等时光非礼了梦想. 提交于 2020-01-01 18:17:31

问题


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.

I'll get the output as "<table><tr><td>item</td></tr></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.


回答1:


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.



来源:https://stackoverflow.com/questions/7013733/convert-string-to-webcontrols-asp-net

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