以编程方式将用户控件加载到 html 文本编写器中

load a user control programmatically in to a html text writer(以编程方式将用户控件加载到 html 文本编写器中)

本文介绍了以编程方式将用户控件加载到 html 文本编写器中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将用户控件呈现为字符串.应用程序设置为允许用户使用令牌,并且用户控件在找到令牌的位置呈现.

I am trying to render a user control into a string. The application is set up to enable user to use tokens and user controls are rendered where the tokens are found.

StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter writer = new HtmlTextWriter(sw);

Control uc = LoadControl("~/includes/HomepageNews.ascx");
uc.RenderControl(writer);
return sb.ToString();

该代码呈现控件,但在控件的 Page_Load 中调用的所有事件均未触发.控件中有一个中继器需要触发.

推荐答案

很长一段时间以来,我一直在使用 Scott Guthrie 在他的博客中提供的以下代码:

I've been using the following code provided by Scott Guthrie in his blog for quite some time:

public class ViewManager
{
    public static string RenderView(string path, object data)
    {
        Page pageHolder = new Page();
        UserControl viewControl = (UserControl) pageHolder.LoadControl(path);

        if (data != null)
        {
            Type viewControlType = viewControl.GetType();
            FieldInfo field = viewControlType.GetField("Data");
            if (field != null)
            {
                field.SetValue(viewControl, data);
            }
            else
            {
                throw new Exception("ViewFile: " + path + "has no data property");
            }
        }

        pageHolder.Controls.Add(viewControl);
        StringWriter result = new StringWriter();
        HttpContext.Current.Server.Execute(pageHolder, result, false);
        return result.ToString();
    }
}

object data 参数,可将数据动态加载到用户控件中,并可用于通过数组或类似的方式将多个变量注入到控件中.

The object data parameter, enables dynamic loading of data into the user control, and can be used to inject more than one variable into the control via an array or somethin similar.

此代码将触发控件中的所有正常事件.

This code will fire all the normal events in the control.

你可以在这里阅读更多信息

问候杰斯珀·豪格

这篇关于以编程方式将用户控件加载到 html 文本编写器中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:以编程方式将用户控件加载到 html 文本编写器中

基础教程推荐