How to a string can turn a UserControl

大憨熊 提交于 2019-12-23 04:38:24

问题


Is there any ways/possibilities that I can replace a string with a UserControl?

apart from LoadControl and adding it to another control like page or placeholder.

The reason is that a user add a content on the page and put a string like {uc:test} and I would like to parse this text and replace {uc:test} with a UserControl.

in other words ; The user input will be "bla bla bla {uc:test} bla bla", when I retrieve it from database how can I inject usercontrol and replace it with {uc:test}

thanks.


回答1:


Try the LoadControl method to dynamically load user controls and add them to your page during postback.

Control someControl = LoadControl("~/SomeControl.ascx");

You could... Add it to your page's control collection:

        this.Page.Controls.Add(someControl);

Or... Add it to another control's control collection

        someExistingPlaceHolder.Controls.Add(someControl);

How about getting the tags like this using regex

List<string> fields = new List<string>(); 
foreach(Match match in Regex.Matches(str, @"\{([^\}]*)\}")) { 
    fields.Add(match.Groups[1].Value); 
} 



回答2:


If you want all of the user input to be respected, including any control references they've included, use ParseControl:

string markup = input.Replace("{","<").Replace("}",">");
Control control = this.Page.ParseControl(markup);

this.Page.Controls.Add(control);

This will create a new Control which represents all the text ("blah blah") as Literal child controls, as well as create new instances of <uc:test> as nested child controls.



来源:https://stackoverflow.com/questions/1535365/how-to-a-string-can-turn-a-usercontrol

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