How to dynamically render asp.net controls from string?

前端 未结 2 1979
太阳男子
太阳男子 2020-12-11 23:47

Let\'s say I have a string that I retrieve from a DB like:
\"Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore e

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-12 00:10

    public class Program
        {
            static void Main(string[] args)
            {
                ParserBase parser = new ParserBase();
    
                Console.WriteLine(parser.DynamicRenderControl(parser.Parse("")));
                Console.ReadLine();
            }
        }
    
        public class ParserBase
        {
            public virtual Dictionary Parse(string stringToParse)
            {
                //...
                // parse the stringToParse
                //...
                Dictionary parsedPropertiesValues = new Dictionary();
                parsedPropertiesValues.Add("NavigateUrl", @"http://www.koolzers.net");
                return parsedPropertiesValues;
            }
    
            protected virtual void SetProperty(T obj, string propertyName, string value) where T : WebControl
            {
                typeof(T).GetProperty(propertyName).SetValue(obj, value, null);
            }
    
    
            public string DynamicRenderControl(Dictionary parsedPropertiesValues) where T : WebControl, new()
            {
                StringBuilder sb = new StringBuilder();
                using (T control = new T())
                {
                    foreach (KeyValuePair keyValue in parsedPropertiesValues)
                    {
                        SetProperty(control, keyValue.Key, keyValue.Value);
                    }
    
                    using (StringWriter tw = new StringWriter(sb))
                    {
                        using (HtmlTextWriter w = new HtmlTextWriter(tw))
                        {
                            control.RenderControl(w);
                        }
                    }
    
                }
                return sb.ToString();
            }
        }
    

提交回复
热议问题