且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-10-02 12:53:10

很长一段时间以来,我一直在使用 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.

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

问候杰斯珀·豪格