c# - 以编程方式呈现 Web UserControl

标签 c# asp.net user-controls

我在他们自己的小项目中有很多 UserControl 对象(ascx 文件)。然后我在两个项目中引用这个项目:REST API(这是一个类库项目)和主网站。

我相信这在网站上很容易,只需在任何 Panel 或 ASP.NET 控件中使用 Controls.Add 即可。

但是,API 呢?有什么方法可以通过知道控件的类型来呈现此控件的 HTML? RenderControl方法不会将任何 HTML 写入编写器,因为控件的生命周期甚至还没有开始。

请记住,我在 Web 项目中没有控件,所以我没有 ascx 文件的虚拟路径。所以 LoadControl方法在这里不起作用。

所有控件实际上都派生自同一个基本控件。我可以在这个基类中做些什么来让我从一个全新的实例加载控件吗?

最佳答案

这是我最近所做的,效果很好,但如果您在 ASP.NET 应用程序中使用它,请理解回传将不起作用。

 [WebMethod]
 public static string GetMyUserControlHtml()
 {
     return  RenderUserControl("Com.YourNameSpace.UI", "YourControlName");
 }

 public static string RenderUserControl(string assembly,
             string controlName)
 {
        FormlessPage pageHolder = 
                new FormlessPage() { AppRelativeTemplateSourceDirectory = HttpRuntime.AppDomainAppVirtualPath }; //allow for "~/" paths to resolve

        dynamic control = null;

        //assembly = "Com.YourNameSpace.UI"; //example
        //controlName = "YourCustomControl"
        string fullyQaulifiedAssemblyPath = string.Format("{0}.{1},{0}", assembly, controlName);

        Type type = Type.GetType(fullyQaulifiedAssemblyPath);
        if (type != null)
        {
            control = pageHolder.LoadControl(type, null);
            control.Bla1 = "test"; //bypass compile time checks on property setters if needed
            control.Blas2 = true;

        }                          

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


public class FormlessPage : Page
{
    public override void VerifyRenderingInServerForm(Control control)
    {
    }
}

关于c# - 以编程方式呈现 Web UserControl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8088427/

相关文章:

c# - EF Core 嵌套的 Linq 选择结果在 N + 1 个 SQL 查询中

asp.net - 公共(public) ASP.NET 应用程序安全注意事项

wpf - 调整托管数百个类似控件的 WPF 应用程序性能

c# usercontrol 设置自定义属性的选项列表

c# - 将 SQL NVARCHAR 的值返回到 C# 字符串

c# - 如何将自定义控件派生的 TabItem 添加到 WPF 中的 TabControl?

asp.net - 调用aspx页面随机返回图像慢

c# - 从控件子类化 ParentForm WndProc

c# - 使用递归函数?

c# - 从 c# 后面的代码编写页面加载 javascript 函数