How to a string can turn a UserControl

2019-06-09 08:46发布

问题:

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.