简体   繁体   English

如何从字符串动态呈现asp.net控件?

[英]How to dynamically render asp.net controls from string?

Let's say I have a string that I retrieve from a DB like: 假设我有一个字符串,我从DB中检索到:
"Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et {{Hyperlink|navigateurl='/foo.aspx'}} dolore magna aliquyam." “Lorem ipsum dolor sit amet,consetetur sadipscing elitr,sed diam nonumy eirmod tempor invidunt ut labore et {{Hyperlink | navigateurl ='/ foo.aspx'}} dolore magna aliquyam。”

This string may now get assigned to the Text-property of a label. 现在可以将此字符串分配给标签的Text-property。
What I want is to parse {{Hyperlink|navigateurl='/foo.aspx'}} and replace it with 我想要的是解析{{Hyperlink | navigateurl ='/ foo.aspx'}}并将其替换为

<asp:HyperLink ID="IDLink" runat="server" Text="foo" NavigateUrl="/foo.aspx"/>

and assign the whole text including the HyperLink-Control to the Label. 并将包括HyperLink-Control在内的整个文本分配给Label。

Is that even possible? 这甚至可能吗? I think I could use reflection to create the control and set the properties. 我想我可以使用反射来创建控件并设置属性。 (the HyperLink-Control was just an example) But can I manage to insert the asp.net control back into the string to ensure the hyperlinks rendering as server contorl? (HyperLink-Control只是一个例子)但是我可以设法将asp.net控件插回到字符串中以确保超链接呈现为服务器控件吗?

I hope you understand what I want. 我希望你明白我的意思。 If not, feel free to post comments. 如果没有,请随时发表评论。

Edit1: EDIT1:

what do you mean by "assign the whole text including the HyperLink-Control to the Label."? 你是什​​么意思“将整个文本包括HyperLink-Control分配给标签。”? can you explain a bit, the reason for doing so ? 你可以解释一下,这样做的原因是什么?

I think it won't work to assign the control into the string, because a asp.net control cannot be fit into a string. 我认为将控件分配给字符串是行不通的,因为asp.net控件不能适合字符串。

After some thinking I found a way to achieve my goal. 经过一番思考,我找到了实现目标的方法。 That would be to create a placeholder (I name it A). 那就是创建一个占位符(我将其命名为A)。 Therein some Literal control will be added. 其中将添加一些Literal控件。 In addition I would create a placeholder (I name it B), add my Hyperlink into B, and add A into B. But I think is way to overkill. 另外我会创建一个占位符(我将其命名为B),将我的超链接添加到B中,并将A添加到B中。但我认为这是过度杀伤的方法。

The reason why I started thinking about this, was to gain access to Server.MapPath without replacing occurences in the string. 我开始考虑这个问题的原因是为了获得对Server.MapPath的访问而不替换字符串中的出现。 I want to be able to use relative paths in my CMS, that get rendered like the NavigateUrl property from a hyperlink. 我希望能够在CMS中使用相对路径,从远程超链接获取类似NavigateUrl属性的路径。 Nevertheless I think my question with the dynamically creation is worth thinking about 不过我觉得我对动态创作的问题值得考虑

public class Program
    {
        static void Main(string[] args)
        {
            ParserBase parser = new ParserBase();

            Console.WriteLine(parser.DynamicRenderControl<HyperLink>(parser.Parse("")));
            Console.ReadLine();
        }
    }

    public class ParserBase
    {
        public virtual Dictionary<string, string> Parse(string stringToParse)
        {
            //...
            // parse the stringToParse
            //...
            Dictionary<string, string> parsedPropertiesValues = new Dictionary<string, string>();
            parsedPropertiesValues.Add("NavigateUrl", @"http://www.koolzers.net");
            return parsedPropertiesValues;
        }

        protected virtual void SetProperty<T>(T obj, string propertyName, string value) where T : WebControl
        {
            typeof(T).GetProperty(propertyName).SetValue(obj, value, null);
        }


        public string DynamicRenderControl<T>(Dictionary<string, string> parsedPropertiesValues) where T : WebControl, new()
        {
            StringBuilder sb = new StringBuilder();
            using (T control = new T())
            {
                foreach (KeyValuePair<string, string> keyValue in parsedPropertiesValues)
                {
                    SetProperty<T>(control, keyValue.Key, keyValue.Value);
                }

                using (StringWriter tw = new StringWriter(sb))
                {
                    using (HtmlTextWriter w = new HtmlTextWriter(tw))
                    {
                        control.RenderControl(w);
                    }
                }

            }
            return sb.ToString();
        }
    }

I believe this is possible if you split your text into 2 labels instead of one. 我相信如果你将文本分成两个标签而不是一个标签,这是可能的。 I wrote up a quick sample to demonstrate. 我写了一个快速示例来演示。 When you parse your string from the db, if there is text before and after your dynamic control than just set the BeginText and EndText properties of DynamicControl. 从数据库解析字符串时,如果动态控件之前和之后有文本,则只需设置DynamicControl的BeginText和EndText属性。

public class DynamicControl
{
    public String BeginText { get; set; }
    public String EndText { get; set; }
    public String ControlName { get; set; }
    public Dictionary<String, String> ControlProperties { get; set; }
}

public partial class _Default : System.Web.UI.Page 
{
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        //read strings from db
        var dynamicControlStrings = GetStringsFromDB();
        //parse strings into list of dynamicControls
        var dynamicControls = ParseStringsToDynamicControls(dynamicControlStrings);
        foreach (var dynamicControl in dynamicControls)
        {
            CreateControl(dynamicControl.BeginText, dynamicControl.EndText, dynamicControl.ControlName, dynamicControl.ControlProperties);
        }
    }

    private void CreateControl(string beginText, string endText, string controlName, Dictionary<String, String> controlProperties)
    {
        var beginLabel = new Label()
        {
            Text = beginText
        };

        var dynamicControl = GenerateDynamicControl(controlName, controlProperties);        

        var endLabel = new Label()
        {
            Text = endText
        };

        var span = new HtmlGenericControl("span");
        span.Controls.Add(beginLabel);
        span.Controls.Add(dynamicControl);
        span.Controls.Add(endLabel);

        form1.Controls.Add(span);        
    }

    //you would create your dynamic control here (such as the hyperlink) based on the control name and use reflection to set the properties
    private WebControl GenerateDynamicControl(string controlName, Dictionary<String, String> controlProperties)
    {        
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }    
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM