用用户控件替换字符串 [英] Replace a string with a user control

查看:25
本文介绍了用用户控件替换字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何用 UserControl 替换字符串?

How can I replace a string with UserControl?

if string = [$control1$]

if string = [$control1$]

替换为 control1.ascx

replace with control1.ascx

推荐答案

你是说用户控件加载到页面后输出的 HTML 吗?

Do you mean the HTML output by the user control if it is loaded into a page?

试试这个:

using System.Web.UI;

public static string RenderToString(this Control control)
{
    var sb = new StringBuilder();
    using (var sw = new StringWriter(sb))
    using (var textWriter = new HtmlTextWriter(sw))
    {
        control.RenderControl(textWriter);
    }

    return sb.ToString();
}

更新:

啊——首先你需要字符串的解析器(这似乎是如何将一个字符串变成一个用户控件)about) - 这将为您提供要替换的用户控件的名称.

Ahh - first you need the parser for the strings (which appears to be what How to a string can turn a UserControl is about) - this will give you the names of the user controls to replace.

来自@Boon 对该问题的回答:

From @Boon's answer to that question:

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

那么我们需要一个函数来加载控件:

So then we need a function to load the controls:

Dictionary<string, string> GetControls( List<string> controlNames )
{
    Dictionary<string, string> retval = new Dictionary<string, string>();
    foreach( string controlName in controlNames ) {
    {
        // load the control
        Control ctrl = LoadControl("~/AllowedDynamicControls/" + controlName + ".ascx");

        // add to the dictionary
        retval.Add(controlName, ctrl.RenderToString() );
    }
}

然后使用这个结果来替换标记:

Then use the results of this to replace the tokens:

var tokensInString = FindTokens(input);
var tokenContent = GetControls( tokensInString );

foreach( var pair in tokenContent ) 
{
    input = input.Replace( "[$" + pair.Key + "$]", pair.Value);
}

可能有更有效的方法来做到这一点 - 我用替换作为一个简单的例子.

There's probably more efficient way to do this - I've used a replace as a quick example.

这篇关于用用户控件替换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆