C# 以编程方式呈现web用户控件

C# 以编程方式呈现web用户控件,c#,asp.net,user-controls,C#,Asp.net,User Controls,我在自己的小项目中有一堆UserControl对象(ascx文件)。然后我在两个项目中引用了这个项目:RESTAPI(一个类库项目)和主网站 我相信这在网站上会很容易,只需使用控件。在任何面板中添加,或者ASP.NET控件都可以 但是,API呢?是否有任何方法可以简单地通过知道控件的类型来呈现该控件的HTML?该方法不会向编写器写入任何HTML,因为控件的生命周期甚至还没有开始 请记住,我在web项目中没有控件,因此我没有指向ascx文件的虚拟路径。所以这个方法在这里不起作用 所有控件实际上都派

我在自己的小项目中有一堆
UserControl
对象(
ascx
文件)。然后我在两个项目中引用了这个项目:RESTAPI(一个类库项目)和主网站

我相信这在网站上会很容易,只需使用
控件。在任何
面板中添加
,或者ASP.NET控件都可以

但是,API呢?是否有任何方法可以简单地通过知道控件的类型来呈现该控件的HTML?该方法不会向编写器写入任何HTML,因为控件的生命周期甚至还没有开始

请记住,我在web项目中没有控件,因此我没有指向
ascx
文件的虚拟路径。所以这个方法在这里不起作用


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

这是我最近做的,效果很好,但是如果你在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)
    {
    }
}

看起来不错,瑞克。我只是想在我的结构中实现这一点。但我注意到一件事-
HtmlForm form=new HtmlForm()。从未使用此变量,因为
form.Controls.Add
已注释掉?我遗漏了什么吗?我会更新,有一种方法可以处理常规表单,但是如果控件没有表单标记,或者没有以编程方式添加表单标记,则会出现运行时错误。这就是FormleSpage类为您绕过的内容。